鉴于这个应用程序:
#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
编译才能得到我期望的输出结果(示例)。
我曾认为,如果这样做会影响观察到的行为,编译器可能不会省略掉一些内容,但 GCC、clang 和 MSVC 似乎正在这样做。
我是错过了某些通用规则,还是这仅适用于使用临时对象初始化的情况?
X b = 2;
是初始化,无论如何都不使用赋值运算符。 - Bo Persson