首页 > 编程语言 > 详细

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

时间:2018-06-09 18:37:35      阅读:154      评论:0      收藏:0      [点我收藏+]

记住: 

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

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)
{
}

 

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

原文:https://www.cnblogs.com/pfsi/p/9160297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!