Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a pointer to object returned with NRVO

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?

like image 458
Scott Oliver Avatar asked Jun 30 '16 13:06

Scott Oliver


1 Answers

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.

like image 78
Lightness Races in Orbit Avatar answered Nov 12 '22 05:11

Lightness Races in Orbit