【发布时间】:2017-02-08 21:48:04
【问题描述】:
鉴于此应用程序:
#include <iostream>
struct X {
X(int _x) { x = _x + 1; }
X(const X& that) { x = that.x + 10; }
X& operator=(const X& that) { x = that.x + 100; return *this; }
X(X&& that) { x = that.x + 1000; }
X& operator=(X&& that) { x = that.x + 10000; return *this; }
int x;
};
int main() {
X a(1);
std::cout << "a.x=" << a.x << std::endl;
X b = 2;
std::cout << "b.x=" << b.x << std::endl;
X c = X(3);
std::cout << "c.x=" << c.x << std::endl;
X d = a;
std::cout << "d.x=" << d.x << std::endl;
}
我预计输出是:
a.x=2
b.x=1003
c.x=1004
d.x=12
但我得到的是:
a.x=2
b.x=3
c.x=4
d.x=12
获得预期输出的唯一方法是使用 -fno-elide-constructors (example) 进行编译
我认为如果这样做会影响观察到的行为,编译器可能不会省略某些内容,但 GCC、clang 和 MSVC 似乎正在这样做。
我是否遗漏了一些一般规则,或者它是特定于使用临时对象初始化的?
【问题讨论】:
标签: c++ c++11 language-lawyer