Why C++ default initialization doesn't zero-initialize non-class type members

笑着哭i 提交于 2020-01-16 00:46:28

问题


why the standard decides to do nothing for non-class type members during a default initialization but performs zero initialization during value initialization?

Would it be safer if zero initialization is always performed on non-clss type memebers?


回答1:


One of the basic principles of design in the language is that you should not pay for something you don't need. If you want your members initialized, you can ask the compiler to do so, but if you don't want that, the cost won't be forced onto you.

Default initialization will only initialize those things that need to be initialized, that is, the members that have a non-trivial default constructor, as that constructor is meant to set some invariants that are important for the object. Note that the distinction is not class-type vs. fundamental type, but rather whether there is a trivial constructor or not:

struct POD { int a; int b; int c; };
struct V { virtual void f(); };
struct Type {
   std::string str;       // default initialization calls default constructor
   V           obj;       //  " calls default constructor: vptr must be set
   POD         pod;       // default initialization leaves this untouched
};



回答2:


If you're going to initialize the data yourself later, then you don't want to pay for initializing the memory to zero only to have it overwritten.




回答3:


I've never heard Bjarne, or another member of the standards committee, say that language safety is a guiding principle of C++ language design. Certainly, it is for Java and other languages, but the C++ language designers are more likely to favour efficiency:

C++ is lean and mean. The underlying principle is that you don't pay for what you don't use.

-Bjarne Stroustrop



来源:https://stackoverflow.com/questions/19235864/why-c-default-initialization-doesnt-zero-initialize-non-class-type-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!