If I write a factory method that instantiates an object locally and then returns by value, intending to take advantage of NRVO (as per some of the answers here: c++11 Return value optimization or move?), will a pointer/reference to the local object point to the object that is assigned the return value of the method?
Object ObjectBuilder::BuildObject( void )
{
Object obj;
//this->ObjectReference = obj; //Disregard this
//OR
this->ObjectPtr = &obj;
return obj;
}
In use:
ObjectBuilder builder;
Object newObject = builder.BuildObject();
Does builder.ObjectPtr refer to newObject?
No.
You are storing a dangling pointer.
Your program, when it uses this pointer, will have undefined behaviour and that is that.
No amount of convenient optimisation is going to save you from your fate.
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