Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When copy constructor starts working?

Tags:

c++

#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?

like image 534
IAmBlake Avatar asked Dec 18 '22 13:12

IAmBlake


1 Answers

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.

like image 104
Bathsheba Avatar answered Jan 05 '23 18:01

Bathsheba