Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion in C++ constructor

#include <iostream>
using namespace std;

class Obj {
public:
    Obj(){cout <<"create obj" << endl;}
    Obj(const Obj& other){cout<<"copy create obj"<<endl;}
    ~Obj(){cout<<"destructed obj"<<endl;}
};

int main() {
    Obj(Obj((Obj())));
    cout<<"---- exit main ----"<<endl;
}

I have no idea why this program only prints out 1 create obj and 1 destructed obj. Help.

like image 877
chenyuandong Avatar asked Jan 04 '23 07:01

chenyuandong


1 Answers

Because of Copy Elision. Read more about it here. Your compiler understands, that it can avoid copying the object around, and just creates one object.

like image 195
gsamaras Avatar answered Jan 13 '23 11:01

gsamaras