#include <iostream>
using namespace std;
class myclass {
public:
myclass();
myclass(const myclass &o);
myclass f();
};
myclass:: myclass(){
cout<<"Constructing normally"<<endl;
};
myclass:: myclass(const myclass &o){
cout<<"Constructing copy"<<endl;
};
myclass myclass::f(){
myclass temp;
return temp;
};
int main(){
myclass obj;
obj = obj.f();
return 0;
}
I found this example in a book which shows that the output of the program should be:
Constructing normally
Constructing normally
Constructing copy
But when i compile it in my compiler it only shows the output written below
Constructing normally
Constructing normally
What is actually happening inside?
Your constructor has a side effect - namely the cout
call. So the compiler cannot optimise out the copy taken in obj = obj.f();
.
But the C++ standard does allow it to optimise out the deep copy taken in
myclass myclass::f(){
myclass temp;
return temp;
};
despite there being a side effect. That allowable strategy is called Named Return Value Optimisation.
Sadly your book is really rather outdated, or factually incorrect from the outset! You could use it for kindling when lighting those cosy fires this coming winter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With