《Effective C++》读书笔记之四 Item 4. Make sure that objects are initialized before they're used

     这篇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, because
the 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值