0

I have an understanding that copy constructor will be called when an object is created from an already existing object and also when a function returns object by value. So why in the below code the copy constructor is not called but the default constructor?

class A {
public:
    A() { cout << "A" << endl; }
    A(A &) { cout << "A&" << endl; }
    A(const A &) { cout << "const A&" << endl; }
};
A fun() {
    class A a;
    return a;
}
int main() {
    class A a = fun(); // output: A
}
Wolf
  • 9,246
  • 7
  • 59
  • 101
Ibrahim Quraish
  • 3,663
  • 2
  • 24
  • 32
  • If you google for "copy constructor not called", you get many existing answers to this question. – Joseph Mansfield Feb 11 '14 at 11:08
  • see [Copy elision - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Copy_elision) – Wolf Feb 11 '14 at 11:17
  • Its because of 'Return value optimization'. Just turn off all optimizations and then test. – Nitesh Feb 11 '14 at 11:18
  • [Nitesh Chordiya](http://stackoverflow.com/users/194372/nitesh-chordiya), turning off all optimizations using **g++ -O** switch did not change the result – Ibrahim Quraish Feb 13 '14 at 06:42

1 Answers1

3

Short answer: compiler optimizations.

  • First, the a object from your function is created directly in the scope of the main function, in order to avoid having to copy (or move in C++11) the local parameter out of the scope of the function via the function's return. This is return value optimization.

  • Then, in main, the statement becomes equivalent to class A a = A() and again the compiler is allowed to the create the a object in place, without copying from a temporary object. This is copy elision.

This is allowed even if the copy constructor (which is bypassed entirely) has side-effects, like in your example.

bolov
  • 65,999
  • 14
  • 127
  • 202