Why copy constructor is not used 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 
+4
source share
2 answers

You declared the copy constructor as follows:

 stri(stri &s1); 

This line, in particular the expression on the right side of = , creates a temporary:

 stri s3 = s1+s2; // ^^^^^ the result of this expression is a temporary 

Since this is copy initialization, she needs to call the copy constructor. But since temporary users cannot communicate with references to non-constant objects, you get an error message.

When you comment on the copy constructor, the compiler generates it for you. His signature then

 stri(stri const&); 

Now it refers to a constant, and the temporary can communicate with it. The fix should now be obvious.

Please note that even if an accessible copy constructor is required to correctly initialize the copy, the compiler can choose how to reject the call to it during optimization, even if this change changes the observed behavior of your program.

+13
source

Let me vacuum my crystal ball and guess that the error you are getting is somewhere along the line โ€œtemporary cannot be attached to the linkโ€. This is because your copy constructor takes its parameter as stri & instead of const stri & ; in other words, a reference to non-constant. Such links cannot be attached to temporary. s1 + s2 returns a temporary value, so the ctor copy call fails.

If you are not doing really monstrous things in your copy of ctor (changing the object copied from), change it to accept its parameter as const stri & .

+3
source

Source: https://habr.com/ru/post/1483566/


All Articles