为什么不在这里调用拷贝构造函数 [英] Why copy constructor not invoked here
问题描述
stri(){}
stri(char *s);//constructor used to initilize object with constant string
stri(stri &s1);//copy constructor performs memberwise copy
friend stri operator+(stri &s1,stri &s2);//conccats two string objects
void operator=(stri &s);//performs memberwise copy
//In main
//s1 and s2 are initilized with constant strings
stri s3=s1+s2; //Gives error? However when copy constructor is removed works fine
推荐答案
复制构造函数如下:
stri(stri &s1);
这一行,特别是 =
,产生一个临时:
This line, specifically the expression on the right hand side of =
, produces a temporary:
stri s3 = s1+s2;
// ^^^^^ the result of this expression is a temporary
是复制初始化,它需要调用复制构造函数。但是由于临时不能绑定到对非const对象的引用,你会得到一个错误。
As this is copy initialization, it needs to call the copy constructor. But as temporaries cannot bind to references to non-const objects, you get an error.
当你注释掉复制构造函数时,编译器为你生成一个。其签名是
When you comment out the copy constructor, the compiler generates one for you. Its signature is then
stri(stri const&);
现在它引用const并且一个临时文件可以绑定到它。
Now it takes a reference to const and a temporary can bind to it. The fix should be obvious now.
请注意,即使良好的复制初始化需要一个可访问的复制构造函数,编译器可以选择在优化期间舍弃对它的调用,即使该节奏改变了您的程序的可观察行为。
Note that even though a well formed copy initialization requires an accesible copy constructor, the compiler can choose to elide the call to it during optimization, even when that elision changes the observable behavior of your program.
这篇关于为什么不在这里调用拷贝构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!