鉴于此应用程序:
#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似乎正在这样做。
我是否缺少一些通用规则或者是否特定于临时对象初始化?