Mixture

身未动,心已远

导航

effective C++ 4 Make sure objects are initialized before they are used

由于读取未初始化的值可能导致的结果不确定,为了避免出错,在用它们之前一定要初始化。

1.对于内置类型以外的对象,要在构造函数里完成对象每一个成员的初始化。使用成员初值列,而不是在构造函数内赋值

需要搞清楚的是赋值和初始化的区别,举个书上的例子:

class PhoneNumber {...};
class ABEntry {
public:
    ABEntry(const std::string &name, const std::string& address, const std::list<PhoneNumber> &phones);
private:
    std::string theName;
    std::string theAddress;
    std::list<PhoneNumber> thePhones;
    int numTimesConsulted;
};

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

上面都是赋值,这样就白白浪费了这些成员变量的default构造函数。(内置类型int不算)

所以使用:

theName(name);

上面这样的copy构造函数就比较高效。

 

2.在初值列中列出所有成员变量

3.初值列中各个成员变量的顺序最好和他们声明的顺序一样(防止出现后面的变量用到前面的变量这种和顺序相关的问题)

4. 还需要注意的是non-local static 对象的初始化顺序。

因为如果这些non-local static对象出现在不同的编译单元中,那么它们的初始化顺序是完全不确定的。为了防止出现由顺序导致的问题,可以把这些non-local static对象变成成员函数的local static 对象,通过返回他们的引用来获得这些对象,这样就可以人为的确定他们的初始化顺序了。(限于单线程程序中)

 

 

 

posted on 2014-04-02 18:07  parapax  阅读(151)  评论(0编辑  收藏  举报