C++ 中的堆栈对象创建- 替代语法
我对 C++ 中的一个问题感到困惑。
当使用默认构造函数在堆栈上创建对象时,我认为以下两种语法符号中的任何一个都会给出相同的结果:
class MyClass { public: int i; }
int main()
{
MyClass a = MyClass();
MyClass b;
}
但是,第一个语法将字段初始化为零,而第二个语法使字段保持未初始化。所以我的问题是:
- 为什么会这样?我认为 C++ 中的字段不应该自动初始化。
- 这两种语法之间还有其他差异吗?
- 这些语法变体是否有单独的名称来相互区分?
我目前正在使用 Microsoft Visual C++ 2010 Express。 谢谢!
Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?
I am confused about an issue in C++.
When creating an object on the stack using the default constructor, I thought either one of the following two syntax notations would give the same result:
class MyClass { public: int i; }
int main()
{
MyClass a = MyClass();
MyClass b;
}
However, the first syntax initializes the field to zero, whereas the second one leaves the field uninitialized. So my questions are:
- Why is this so? I thought fields in C++ were not supposed to be automatically initialized.
- Is there any other differences between the two syntaxes?
- Do these syntax variations have separate names to distinguish them from each other?
I’m currently using Microsoft Visual C++ 2010 Express.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您从
MyClass
的值初始化实例中复制初始化a
。来自 C++03 标准,§8.5/7:从 §8.5/5 开始:
在第二种情况下,如果
MyClass
不是 POD 类型,则以某种方式声明b
,使其默认初始化—— §8.5/5:但是,由于
MyClass
是 POD 类型,因此b
未初始化 - §8.5/9:In the first, you copy-initialize
a
from a value-initialized instance ofMyClass
. From the C++03 standard, §8.5/7:And from §8.5/5:
In the second, you declare
b
in a manner that would cause it to be default-initialized ifMyClass
were not a POD type -- §8.5/5:However, because
MyClass
is a POD type,b
is uninitialized -- §8.5/9:基本上,这是该语言中的一个(相对)简单的 WTF,默认情况下不会初始化原始类型。第一个语法显式地初始化它们,而第二个则没有。用户定义的类型总是会被初始化,所以只有在构造函数中没有初始化它才有意义,如果不调用需要它们的UDT的init函数,就会出错。
不做任何疯狂事情的 UDT 不应该需要第一种语法,使用第二种语法是正常的。
Basically, this is a (relatively) simple WTF in the language, where primitive types will not be initialized by default. The first syntax explicitly initializes them- the second doesn't. User-defined types will always be initialized, so it's only meaningful if you don't initialize it in the constructor, and it will be an error if you don't call the init functions of UDTs that need them.
UDTs that do not do anything insane should not require the first syntax and it's normal to use the second.