From the code below below I was expecting for class CA that the following would be called
- constructor creating the temporary object to be returned by the function
foo - copy constructor to create the variable to be passed to the variable
ain the main - another copy constructor that would create the
avariable from the value returned by the function.
Why it is not the case? The result I have is just
A
While I was expecting
ABB
So only the constructor is called. Is compiler optimizing something behind the scenes or have I missed some C++ concept?
class CA{
public:
CA(){ std::cout << "A"; }
CA( const CA& ){ std::cout << "B"; }
CA& operator=(const CA& ){ std::cout << "C";return *this; }
};
CA foo(){
return CA();
}
int main(){
CA a = foo();
}
Spot on! It’s called copy elision. Look up RVO and NRVO on google. You should also look up the rule of three.
Copy elision is the only optimization the compiler is allowed to perform that affects observable behavior. You shouldn’t place important logic in the copy constructor for that reason.