Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't print twice deconstruct for this C++ code sample?

Tags:

c++

copy

using namespace std;

Object returnObject(){
    Object o;  
    return o;  //place A
 }

int main() {
    Object CopiedO=returnObject();  
    return 0;  //Place B
}

the object definition is:

Object::Object() {
    cout<<"Object::Object"<<endl;
}

Object::~Object() {
    cout<<"Object::~Object"<<endl;
}

Object::Object(const Object& object) {
    cout<<"Object::CopyObject"<<endl;
}

the result is:

/*Object::Object
Object::~Object*/

As I understand, both o and CopiedO in will be deconstructed, but why only once Object::~Object be printed?

I think there is no inline and the copied o is copy of o .but it can't print Object::CopyObject

like image 811
jiafu Avatar asked Oct 01 '22 22:10

jiafu


1 Answers

The compiler is eliding the copy. Since it knows that the returned object from the function has as only purpose to initialize CopiedO, it is merging both objects into one and you will see only one construction, one destruction and no copy-constructions.

like image 183
David Rodríguez - dribeas Avatar answered Oct 05 '22 10:10

David Rodríguez - dribeas