c++ - 使用 std::vector 的 std::unique_ptr

标签 c++ vector stl unique-ptr

我刚开始使用智能指针,到目前为止只使用过unique_ptr。我正在创建一个游戏,我正在使用 unique_ptrvector 来存储我的游戏状态。

这是我的 vector 代码:

std::vector<std::unique_ptr<GameState>> gameStates;

这是我的问题。以下功能是否可以控制我的 vector :

void GameStateManager::popGameState(){
    if (getCurrentGameState() != nullptr)
        gameStates.pop_back();
}

void GameStateManager::pushGameState(GameState *gameState){
    gameStates.push_back(std::unique_ptr<GameState>(gameState));
}

GameState *GameStateManager::getCurrentGameState(){
    return gameStates.back().get();
}

我担心使用原始指针作为参数并返回当前游戏状态会消除使用智能指针的意义。这是执行此操作的好方法吗?

最佳答案

试试这个:

void GameStateManager::pushGameState(std::unique_ptr<GameState> gameState){
    gameStates.push_back(std::move(gameState));
}

std::unique_ptr 无法复制,但可以移动。

我认为它有一些好处。例如,看看这段代码。

std::unique_ptr<GameState> pgs;
...
gsm.pushGameState(pgs); // error!
gsm.pushGameState(std::move(pgs)); // you should explicitly move it

如果你使用原始指针......,

void GameStateManager::pushGameState(GameState *gameState) { ... }

{
    std::unique_ptr<GameState> pgs;
    ...
    gsm.pushGameState(pgs.get()); // IT'S NOT COMPILE ERROR! you can make some mistakes like this..
    gsm.pushGameState(pgs.release()); // you can use it, but I think you will make a mistake sometime, finally.
} // if you use `pgs.get()`, the `GameState` is deleted here, though `gameStates` still contains it.

关于c++ - 使用 std::vector 的 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24283812/

相关文章:

c++ - 如何将 std::wstring 与 std::istringstream 一起使用?

c++ - C++ 抛出装饰有什么用吗?

c++ - 无法在 OS X 10.6.8 上运行 QT 5.1.1

c++ - 使用 stringstream 解析 ifstream 的问题

c++ - 对齐 SSE 的模板 vector 结构

c++ - STL 排序对字符串 vector 与字符串指针 vector 的性能比较

c++ - 与 g++ 的链接选项

c++ std::vector performance [需要引用]

c++ - 关于自定义分配器和 STL 的模板声明、别名和特化说明

c++ - std::map::upper_bound 与 std::upper_bound 性能