PrimRock PrimRock - 1 year ago 77
C++ Question

Are heap elements made with unique_ptr moved to the stack still allocated on the heap?

I'm having trouble understanding the behavior of unique pointers. If I allocate an object on the heap...

std::unique_ptr<GameState> mMenuPtr(new MainMenu);

and then
it to my GameState stack like so...

gameStates.push(std::move(mMenuPtr)); //pointer loses ownership of MainMenu during move

Is the element on the stack still dynamically allocated on the heap ? If so, does the destruction of the stack at end scope free that memory I allocated with new, or do I need some other way of destructing that object to prevent memory leaks?

I know the main purpose of
is to handle deallocation for you, but after losing ownership of its object. I'm kinda clueless what to do...

Looking at the STL API it seems the only option I have is the
's get() function which allows me to re-access that object after I perform
, which is what I want because I still want to be able to access that stack element across multiple files even after the
destroys itself....but what would be the ideal way to do that ?

Like this ?

GameState* statePtr = sScreen.get();

Answer Source

unique_ptr will always free the object, unless release is called.

The GameState object is still allocated on the heap. Ownership of the pointer was passed to the stack/vector. The unique_ptr on the stack will do nothing in its destructor (since its pointer is NULL after the move), and the destructor of the stack/vector will call delete if the stack/vector is destructed before the object is moved again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download