C++03 中默认初始化和值初始化之间的区别?
我一直认为创建一个新对象总是会调用对象的默认构造函数,而构造函数是显式的还是由编译器自动生成的都没有区别。根据这个高度被认为是另一个问题的答案,这在 C++98 和 C++03 之间发生了微妙的变化,现在的工作方式如下:
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
new B; // default-initializes (leaves B::m uninitialized)
new B(); // value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.
谁能告诉我:
- 为什么标准发生了变化,即这有什么好处给予或现在可能以前没有的东西;
- 术语“默认初始化”和“值初始化”到底代表什么?
- 标准的相关部分是什么?
I had always thought that creating a new object would always call the default constructor on an object, and whether the constructor was explicit or automatically generated by the compiler made no difference. According to this highly regarded answer to a different question, this changed in a subtle way between C++98 and C++03 and now works like so:
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
new B; // default-initializes (leaves B::m uninitialized)
new B(); // value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.
Can anyone tell me:
- Why was the standard changed, i.e. what advantage does this give or what is now possible that wasn't before;
- What exacly do the terms "default-initialize" and "value-initialize" represent?
- What's the relevant part of the standard?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道更改的基本原理是什么(或者之前的标准是怎样的),但是关于它是如何的,基本上默认初始化要么调用用户定义的构造函数,要么什么也不做(很多手- 此处挥动:这会递归地应用于每个子对象,这意味着具有默认构造函数的子对象将被初始化,没有用户定义构造函数的子对象将保持未初始化状态)。
这属于“只为你想要的东西付费”的语言哲学,并且在所有与 C 兼容的类型中与 C 兼容。另一方面,您可以请求值初始化,这相当于为将其或初始化为
0的对象调用默认构造函数 code> 转换为其余子对象的适当类型。
这在第 8.5 节初始化器中进行了描述,并且导航起来并不简单。 零初始化、默认初始化和值初始化的定义是第5段:
I do not know what the rationales around the change (or how the standard was before), but on how it is, basically default-initialization is either calling a user defined constructor or doing nothing (lots of hand-waving here: this is recursively applied to each subobject, which means that the subobjects with a default constructor will be initialized, the subobjects with no user defined constructors will be left uninitialized).
This falls within the only pay for what you want philosophy of the language and is compatible with C in all the types that are C compatible. On the other hand, you can request value-initialization, and that is the equivalent to calling the default constructor for objects that have it or initializing to
0
converted to the appropriate type for the rest of the subobjects.This is described in §8.5 Initializers, and it is not trivial to navigate through. The definitions for zero-initialize, default-initialize and value-initialize are the 5th paragraph: