初始化具有不确定值的对象
以下是否会调用未定义的行为?
int x;
int i = x;
参考C++03
(4.1/1) 如果左值引用的对象不是 T 类型的对象 并且不是从 T 派生的类型的对象,或者如果该对象是 未初始化,需要此转换的程序已 未定义的行为。
编辑: 然而,从(3.3.1/1)开始,一个对象可以用它自己的不确定值初始化,为什么呢? IE
int x = x; //not an undefined behaviour
Does the following invoke undefined behavior?
int x;
int i = x;
Reference from C++03
(4.1/1) If the object to which the lvalue refers is not an object of type T
and is not an object of a type derived from T, or if the object is
uninitialized, a program that necessitates this conversion has
undefined behavior.
Edit:
However, from (3.3.1/1) an object may be initialized with its own indetermine value, why is that? i.e.
int x = x; //not an undefined behaviour
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,因为您正在读取未初始化且未分配的变量 (
x
) 的值。Yes, because you're reading the value of a variable (
x
) which was uninitialised and unassigned.正如您的引用中所述,如果
x
未初始化,则它是未定义的。It's undefined if
x
is uninitialized, as said in your quote.唯一要记住的是,这没关系:
但你的例子却不行。
The only thing to remember is that this is okay:
but your example is not.
它调用完美定义的行为。无论 x 在堆栈上分配时的垃圾值是什么,都将按原样分配给 i。
但是,根据您的编译器,您可能会收到有关引用未初始化变量的编译时警告。
It invokes perfectly defined behavior. Whatever garbage value x was when it is allocated on the stack will be assigned to i as is.
Depending on your compiler, however, you may get a compile time warning about referencing an uninitialized variable.
错误。
Wrong.