这篇Item主要讲的是记得在使用之前初始化对象的成员变量,并介绍了几种初始化的方法:
1. Manually initialize objects of built- in type, because C++ only sometimes initializes them itself.
2. In a constructor, prefer use of the member initialization list to assig nment inside the body of the constructor. List data members in the initialization list in the same order they‘re declared in the class.
This constructor yields the same end result as the one above, but it will often be more efficient. The assignment- based version first called default constructors to initialize theName, theAddress, an d thePhones, then promptly assigned new values on top of the default- constructed ones. All the work performed in those default constructions was therefore wasted. The member initialization list approach avoids that problem, becausethe arguments in the initialization list are used as constructor arguments for the various data members.
3. Avoid initialization order problems across translation units by replacing non - local static objects with local static objects.
Base classes are initialized before derived classes (see also Item 12(See 10.8)), and within a class, data members are initialized in the order in which they are declared.To avoid reader confusion, as well as the possibility of some truly obscure behavioral bugs, always list members in the initialization list in the same order as they‘re declared in the class.
A static object is one that exists from the time it‘s constructed until the end of the program. Stack and heap- based objects are thus excluded. Included are global objects, objects defined at namespace scope, objects declared static inside classes, objects declared static inside functions, and objects declared static at file scope. Static objects inside functions are known as local static objects (because they‘re local to a function), and the other kinds of static objects are known as non- local static objects.
This approach is founded on C++‘s guarantee that local static objects are initialized when the object‘s definition is first encountered during a call to that function.
《Effective C++》读书笔记之四 Item 4. Make sure that objects are initialized before they're used