简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM