是`X x = x = X();`legal C ++? [英] Is `X x = x = X();` legal C++?
问题描述
我减少了这个:
struct A
{
int * x;
A() : x( x = new int() )
{
}
};
:
int m = m = 3;
//or
struct X;
//...
X x = x = X();
似乎对我合法。我不明白你为什么要这样做,但它是合法的吗?有没有情况下,你想这样做(不是 int
情况,我意识到这是完全无用的)?
Seems legal to me. I don't see why you'd want to do it, but is it legal? Are there cases where you'd want to do this (not the int
case, I realize that's completely useless)?
推荐答案
这取决于你如何定义法律。它将编译;
It depends on how you define "legal". It will compile; that doesn't mean that it is guaranteed to work.
直到完整语句 X x = ...
执行, x
未初始化。它不是 X
。因此,执行 x = X()
表示创建一个临时 X
并调用 X: :
x
。
Until the full statement X x = ...
executes, x
is uninitialized. It is not an X
yet. Therefore, performing x = X()
means to create a temporary X
and call X::operator=(const X&)
on the uninitialized variable x
.
在非 POD类实例尚未初始化(谁的构造函数尚未被调用)产生未定义的行为。如果 X
是POD类型(或在C ++ 11中很简单),那么它将工作。但否则没有。
Calling a function on a non-POD class instance that has not been initialized (who's constructor has not yet been called) yields undefined behavior. If X
is a POD type (or trivial in C++11), then it will work. But otherwise no.
这篇关于是`X x = x = X();`legal C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!