Confusion in the 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 1 create obj and 1 destructed obj. Reference.

+4
source share
1 answer

Due to copying Elision. More on this. Your compiler understands that he can avoid copying the object around and just creates one object.

+9

Source: https://habr.com/ru/post/1687850/


All Articles