设为首页 加入收藏

TOP

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

C++(www.cppentry.com) can seem rather fickle about initializing the values of objects. For example, if you say this,

  1. int x; 

in some contexts, x is guaranteed to be initialized (to zero), but in others, it’s not. If you say this,

  1. class Point {  
  2.   int x, y;  
  3. };  
  4. ...  
  5. Point p; 

p’s data members are sometimes guaranteed to be initialized (to zero),but sometimes they’re not. If you’re coming from a language whereuninitialized objects can’t exist, pay attention, because this is important.

Reading uninitialized values yields undefined behavior. On some platforms, the mere act of reading an uninitialized value can halt your program. More typically, the result of the read will be semi-random bits, which will then pollute the object you read the bits into, eventually leading to inscrutable program behavior and a lot of unpleasant debugging.

Now, there are rules that describe when object initialization is guaranteed to take place and when it isn’t. Unfortunately, the rules are complicated— too complicated to be worth memorizing, in my opinion. In general, if you’re in the C part of C++(www.cppentry.com) (see Item 1) and initialization would probably incur a runtime cost, it’s not guaranteed to take place. If you cross into the non-C parts of C++(www.cppentry.com), things sometimes change. This explains why an array (from the C part of C++(www.cppentry.com)) isn’t necessarily guaranteed to have its contents initialized, but a vector (from the STL part of C++(www.cppentry.com)) is.


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

评论

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