Effective C++ 筆記 —— Item 4: Make sure that objects are initialized before they’re used
阿新 • • 發佈:2021-06-23
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 objectreturn 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 }