我问,因为当我尝试:
#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.
您正在进行复制构造,但是标准允许将其转换为直接初始化,并且无论调试是否关闭都可以完成,这就是打印未到达的原因.
但是,因为它“应该”是一个复制结构,你需要访问一个,这就是第二个代码不起作用的原因.
总结以上是内存溢出为你收集整理的c – 类型t = Type()是否调用复制构造函数?全部内容,希望文章能够帮你解决c – 类型t = Type()是否调用复制构造函数?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)