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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With