5
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

jiafu
  • 6,130
  • 11
  • 47
  • 72

1 Answers1

4

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.

David Rodríguez - dribeas
  • 198,982
  • 21
  • 284
  • 478