using an std::vector of std::unique_ptr

using an std::vector of std::unique_ptr

本文关键字:std ptr unique vector an using of      更新时间:2023-10-16

我是使用智能指针的新手,到目前为止只使用过unique_ptr。我正在创建一款游戏,我使用vectorunique_ptr来存储我的游戏状态。

这是我的矢量代码:

std::vector<std::unique_ptr<GameState>> gameStates;
这是我的问题。下面的函数可以用来控制向量吗?
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.