我问,因为当我尝试:
#include <iostream> class Test { public: Test(Test const &) { std::cout << "hello"; } Test() { } }; int main() { Test t = Test(); return 0; }
没有输出,但当我改变它
#include <iostream> class Test { Test(Test const &) { std::cout << "hello"; } public: Test() { } }; int main() { Test t = Test(); return 0; }
我明白了:
error C2248: 'Test::Test' : cannot access private member declared in class 'Test'
这没有意义(特别是因为这是一个调试版本).
更新:
即便这样编译!
struct Test { Test(Test &&) = delete; Test(Test const &) = delete; Test() { } }; int main() { Test t = Test(); return 0; }
复制/移动构造函数是必需还是否?
解决方法
In C++ computer programming,copy elision refers to a compiler
optimization technique that eliminates unnecessary copying of objects.
The C++ language standard generally allows implementations to perform
any optimization,provided the resulting program’s observable behavior
is the same as if,i.e. pretending,the program was executed exactly
as mandated by the standard.The standard also describes a few situations where copying can be
eliminated even if this would alter the program’s behavior,the most
common being the return value optimization. Another widely implemented
optimization,described in the C++ standard,is when a temporary
object of class type is copied to an object of the same type.[1] As
a result,copy-initialization is usually equivalent to
direct-initialization in terms of performance,but not in semantics;
copy-initialization still requires an accessible copy
constructor.[2] The optimization can not be applied to a temporary
object that has been bound to a reference.
您正在进行复制构造,但是标准允许将其转换为直接初始化,并且无论调试是否关闭都可以完成,这就是打印未到达的原因.
但是,因为它“应该”是一个复制结构,你需要访问一个,这就是第二个代码不起作用的原因.