PrimRock PrimRock - 2 months ago 19
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
push()
and
move()
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
unique_ptr
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
unique_ptr
's get() function which allows me to re-access that object after I perform
move()
, which is what I want because I still want to be able to access that stack element across multiple files even after the
unique_ptr
destroys itself....but what would be the ideal way to do that ?

Like this ?

GameState* statePtr = sScreen.get();

Answer

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.