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

1. 对象使用之前进行初始化

void Test00()
{
    int x = 0;
    const char* text = "A C-style string";
    double d;
    std::cin >> d;
}

1. 使用初始化列表进行初始化
2. baseClass的初始化早于derivedClass
3. class的成员变量总是以声明的顺序进行初始化,而不是在成员初值列中的顺序

复制代码
class PhoneNumber
{};

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

1. 初始化次序的重要性,tfs在tempDir之前先被初始化,否则tempDir的构造函数会用到尚未初始化的tfs
2. 定义并初始化一个local static对象,以免除"跨编译单元之初始化次序"

复制代码
class FileSystem
{
public:
    size_t numDisks()
    {
        return 1u;
    }
};
FileSystem& tfs()
{
    static FileSystem fs;
    return fs;
}

class Directory
{
public:
    Directory()
    {
        std::size_t disks = tfs().numDisks();
    }
};

Directory& tempDir()
{
    static Directory td;
    return td;
}
复制代码

 

posted @   博瑜图形  阅读(5)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示