码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-06-09 18:55:46      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:number   使用   ati   effect   div   声明   IV   ber   one   

记住: 

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

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:确定对象被使用前已先被初始化

标签:number   使用   ati   effect   div   声明   IV   ber   one   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!