设为首页 加入收藏

TOP

Item 4: Make sure that objects are initialized before they’re used.(4)
2013-10-07 14:26:21 来源: 作者: 【 】 浏览:53
Tags:Item Make sure that objects are initialized before they used.

For objects of built-in type like numTimesConsulted, there is no difference in cost between initialization and assignment, but for consistency, it’s often best to initialize everything via member initialization. Similarly, you can use the member initialization list even when you want to default-construct a data member; just specify nothing as an initialization argument. For example, if ABEntry had a constructor taking no parameters, it could be implemented like this:

  1. ABEntry::ABEntry()  
  2. : theName(),  // call theName’s default ctor;  
  3.   theAddress(),  // do the same for theAddress;  
  4.   thePhones(),  // and for thePhones;  
  5.   numTimesConsulted(0)  // but explicitly initialize  
  6. {}  // numTimesConsulted to zero 

Because compilers will automatically call default constructors for data members of user-defined types when those data members have no initializers on the member initialization list, some programmers consider the above approach overkill. That’s understandable, but having a policy of always listing every data member on the initialization list avoids having to remember which data members may go uninitialized if they are omitted. Because numTimesConsulted is of a built-in type, for example, leaving it off a member initialization list could open the door to undefined behavior.

Sometimes the initialization list must be used, even for built-in types. For example, data members that are const or are references must be initialized; they can’t be assigned (see also Item 5). To avoid having to memorize when data members must be initialized in the member initialization list and when it’s optional, the easiest choice is to always use the initialization list. It’s sometimes required, and it’s often more efficient than assignments.

如果你用到了多重继承,你会发现有时使用初始化列表是避免迷惑编译器的唯一方法。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Item 3: Use const whenever poss.. 下一篇Item 4: Make sure that objects ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: