0
Why is copy constructor not called while function return?
2 ответов
+ 3
Constructor is called only once at object creation, whether it be any of them (normal, copy, parameterized).
You created two objects (one in function f() and one in function main()), that's why it prints "Normal constructor" twice
In Line 24,
you aren't creating a new object but changing a previous one, hence no constructor is called.
Should replace that by
my class a = f();
this will call the copy constructor
+ 2
This is called 'Copy elision'. The compiler optimized the code for you.
Without that technique, your code would've been:
Normal constructor
Normal constructor
Copy constructor
Copy constructor
But the compiler made optimization of omitting 2 copies, which is decent considering the amount of lines of code and the time of 2 copies is saved already.
Copy elision is a feature in C++ that the compiler can omit certain copies by 'itself'. You cannot force a copy elision to occur, meaning that the 2 copies could still happen, except by C++17, in the following the copy elision is guaranteed.
myclass f() {return myclass();}
So what copy does the compiler omitted?
Line 18-19, the local object copies to the return value.
Line 24, directly assign an object with a temporary object.
You can find a detailed Stack Overflow post about copy elision here: https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization/12953145#12953145