拥有一个公共拷贝构造函数将会使小程序 编译,但不会显示副本“Copy”。为什么即使未被调用也需要公共拷贝构造函数?
#include <iostream>
class X
{
public:
X(int) { std::cout << "Construct" << std::endl; }
// Having a public copy constructor will make the little program
// compile, but not showing the side effect "Copy".
private:
X(const X&) { std::cout << "Copy" << std::endl; }
private:
X& operator = (const X&);
};
int main() {
X x = 1;
return 0;
}
X x = 1意味着X x(X(1))就我所知,但它被优化到X x(1); – odinthenerd
这是必需的,以便C++代码在可能或不可以自行决定执行copy elision的实现之间是可移植的。 – jrok
尝试使用'-fno-elide-constructors'标志进行编译。 –