C++ copy constructor invocation
c++
Solution
A copy constructor might not be invoked when you return by value. Some compilers use return value optimization feature.
Read about "Return Value Optimization"
Problem
As far as i know, a copy constructor is invoked in the following scenarios : ``` 1) Pass by value 2) Return by value 3) When you create and initialize a new object with an existing object ``` Here's the program : ``` #include <iostream> using namespace std; class Example { public: Example() { cout << "Default constructor called.\n"; } Example(const Example &ob1) { cout << "Copy constructor called.\n"; } Example& operator=(const Example &ob1) { cout << "Assignment operator called.\n"; return *this; } ~Example() { cout<<"\nDtor invoked"<<endl; } int aa; }; Example funct() { Example ob2; ob2.aa=100; return ob2; } int main() { Example x; cout << "Calling funct..\n"; x = funct(); return 0; } ``` The output is: Default constructor called. Calling funct.. Default constructor called. Assignment operator called. Dtor invoked Dtor invoked Please correct me, IIRC the following sequence of calls should occur : 1) Constructor of x is called 2) Constructor of ob2 is called 3) The function returns and so copy constructor is invoked (to copy ob2 to unnamed temporary variable i.e funct() ) 4) Destructor of ob2 called 5) Assign the unnamed temporary variable to x 6) Destroy temporary variable i.e invoke its destructor 7) Destroy x i.e invoke x's destructor But then why copy constructor is not invoked and also only 2 calls to dtors are there whereas i expect 3. I know compiler can do optimizations, however, is my understanding correct ? Thanks a lot :) Regards lali