effective c++ 条款04:确定对象被使用前已先被初始化

记住: 

对于内置类型以外的任何其它东西,初始化责任落在构造函数身上,确保每个构造函数都将对象的每一个成员初始化。

C++规定,对象的成员变量的初始化动作发生在进入构造函数本体之前。

使用成员初始化列表替换构造函数内的赋值动作。

如果成员变量是const或reference,它们就一定需要初值,不能被赋值。

base class早于derived class被初始化,class的成员变量总是以声明的次序被初始化,不受成员初始化列表中的顺序影响。

为避免”跨编译单元之初始化次序“问题,以local static对象替换non-local static对象。

 

ABEntry::ABEntry(const string& name, const string& address,
                 const list<PhoneNumber>& phones)
    :theName(name),
     theAddress(address),
     thePhones(phones),
     numTimesConsulted(0)
{
    theName = name;          //这些都是赋值,而非初始化
    theAddress = address;
    thePhones = phones;
    numTimesConsulted = 0;
}

 

ABEntry::ABEntry(const string& name, const string& address,
                 const list<PhoneNumber>& phones)
    :theName(name),
     theAddress(address),
     thePhones(phones),
     numTimesConsulted(0)
{
}

 

ABEntry::ABEntry()
    :theName(),             //调用theName的default构造函数
     theAddress(),
     thePhones(),
     numTimesConsulted(0)
{
}

 

posted @ 2018-06-09 17:23  pfsi  阅读(117)  评论(0编辑  收藏  举报