我如何推堆栈unqiue_ptr不做一个副本

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

本文关键字:副本 一个 何推 堆栈 unqiue ptr      更新时间:2023-10-16

最初我做了一个抽象类型为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))

中的.下面

std::unique_ptr被设计为拥有堆内存,你试图给它堆栈内存

你要做的是:

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