Why copy constructor not invoked here

后端 未结 2 705
长情又很酷
长情又很酷 2021-01-13 23:37
stri(){}

stri(char *s);//constructor used to initilize object with constant string

stri(stri &s1);//copy constructor performs memberwise copy

friend stri oper         


        
2条回答
  •  无人共我
    2021-01-13 23:54

    You declared the copy constructor like this:

    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
    

    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&);
    

    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.

提交回复
热议问题