Effective C++ Item 04-确定对象被使用前以先被初始化

来源:互联网 发布:业界良心音乐软件 编辑:程序博客网 时间:2024/05/16 05:25

Item 04-确定对象被使用前以先被初始化(Make sure that object are initialized before they're used)


对象初始化,C++不一定保证对象被初始化

Ex:int x;     在某些语境下会初始化为0

        class Point{

int x,y;

};

Point p;

p的成员变量有时候被初始化(为0)有时候不会。


读取为初始化的值会导致不明确的行为,导致不可预测的程序行为,以及许多令人不愉快的调试过程。

最佳处理办法:永远在使用对象之前先将它初始化。

对于无任何成员的内置类型,必须手工完成

内置意外的任何其他东西,初始化由构造函数负责。

规则:确保每一个构造函数都将对象的每一个成员初始化。

要注意:赋值≠初始化

Ex:

class PhoneNumber{...};

class ABEntry{

public:

ABEntry(const string& name,const string& address,const list<PhoneNumber>& phones);

private:

string theName;

string theAddress;

list<PhoneNumber> thePhones;

int numTimesConsulted;

}

最佳写法:成员初始列操作(member initialization list),总是在初始列中列出所有的成员变量

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


static对象:

1、local static对象(函数内的static对象)

2、non-local static对象(其它)

做法:把non-local static对象搬到自己的专属函数内(这些static对象在函数内被声明为static),这些函数返回一个引用指向它所含的对象。


需要做的事:

1、手工初始化内置型non-member对象

2、使用成员初始列(member initialization lists)对付对象的所有成分

3、“在初始化次序不确定性”氛围下加强你的设计


请记住:

1、为内置型对象进行手工初始化,因为C++不保证初始化它们。

2、构造函数最好使用成员初始列,而不要在构造函数本体内使用赋值操作。初始列列出的成员变量,其排列次序应该和它们在class中的声明次序相同。

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




0 0
原创粉丝点击