PrimRock PrimRock - 3 months ago 14
C++ Question

How do I push to stack with unqiue_ptr without making a copy?

Originally I made a stack that took a abstract type of

GameState*
. So that'll be...

std::stack<GameState*> gameStates


However, someone informed me that if I wanted to retain ownership that I should use C++11's smart pointer
unique_ptr
. So that'll be...

std::stack<std::unique_ptr<GameState>> gameStates


Now whenever I push my
GameState
onto the stack, my compiler complains. I'm doing something wrong apparently...

It says..

no instance of overloaded function matches the argument list


ReigalaSplash splashScreen1(game); //gameState object declaration
gameStates.push(std::move(&splashScreen1)); //move to stack without copying


The red line where the error appears is right over the
.
in
gameStates.push(std::move(&splashScreen1))


How do I fix this ?

Answer

std::unique_ptr is designed to own heap memory, you're trying to give it stack memory.

What you'd like to do is:

std::unique_ptr<GameState> splashScreen1Ptr(new GameState(game));
gameStates.push(std::move(splashScreen1Ptr));
Comments