6
#include<iostream>
using namespace std;

class C{
private:
    int value;
public:
    C(){
        value = 0;
        cout<<"default constructor"<<endl;
    }
    C(const C& c){
        value = c.value;
        cout<<"copy constructor"<<endl;
    }
};
int main(){
    C c1;
    C c2 = C();
}

Output:

default constructor

default constructor

Question:

For C c1; default constructor will be called obviously, for C c2 = C(); I thought default constructor will be called to initialize a temporary object, then copy constructor will be call to initialize c2, It seems that I am wrong. why?

expoter
  • 1,622
  • 17
  • 34

1 Answers1

2

This is an example of copy elision - basically the compiler is allowed to optimize away the copy. Described here: http://en.cppreference.com/w/cpp/language/copy_elision

NexusSquared
  • 157
  • 1
  • 7