Effective C++ 笔记 —— Item 4: Make sure that objects are initialized before they’re used

In a constructor, prefer use of the member initialization list to assignment inside the body of the constructor. List data members in the initialization list in the same order they're declared in the class.

The relative order of initialization of non-local static objects defined in different translation units is undefined.

Avoid initialization order problems across translation units by replacing non-local static objects with local static objects.

class FileSystem { /*...*/ }; // as before
FileSystem& tfs() // this replaces the tfs object; it could be
{ // static in the FileSystem class
    static FileSystem fs; // define and initialize a local static object
    return fs; // return a reference to it
}
class Directory { /*...*/ }; // as before
Directory::Directory(params) // as before, except references to tfs are
{ // now to tfs()
    //...
        std::size_t disks = tfs().numDisks();
    //...
}
Directory& tempDir() // this replaces the tempDir object; it could be static in the Directory class
{ 
    static Directory td(params); // define/initialize local static object
    return td; // return reference to it
}
原文地址:https://www.cnblogs.com/zoneofmine/p/14921496.html