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);
这一行,特别是 =
右边的表达式,产生了一个临时的:
stri s3 = s1+s2;
// ^^^^^ the result of this expression is a temporary
因为这是拷贝初始化,所以需要调用拷贝构造函数。但是由于临时对象无法绑定(bind)到对非常量对象的引用,因此会出现错误。
当您注释掉复制构造函数时,编译器会为您生成一个。那么它的签名就是
stri(stri const&);
现在它需要一个对 const 的引用,一个临时变量可以绑定(bind)到它。修复现在应该很明显了。
请注意,即使格式良好的复制初始化需要可访问的复制构造函数,编译器也可以选择在优化期间省略对它的调用,即使该省略改变了程序的可观察行为。
关于c++ - 为什么这里不调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16835913/