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

c++, copy

Solution

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.

Problem

``` 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

Original source

Related problems