如何在不制作副本的情况下使用unqiue_ptr进行堆叠?

时间:2016-08-28 16:17:24

标签: c++ c++11

最初我制作了一个抽象类型为GameState*的堆栈。那就是......

std::stack<GameState*> gameStates

然而,有人告诉我,如果我想保留所有权,我应该使用C ++ 11的智能指针unique_ptr。那就是......

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

现在每当我将GameState推入堆栈时,我的编译器就会抱怨。我显然做错了......

它说..

no instance of overloaded function matches the argument list

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

出现错误的红线位于.

中的gameStates.push(std::move(&splashScreen1))下方

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

std::unique_ptr旨在拥有堆内存,您尝试将其堆栈内存

您要做的是:

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