簡體   English   中英

使用std :: unique_ptr的std :: vector

[英]using an std::vector of std::unique_ptr

我是使用智能指針的新手,到目前為止只使用了unique_ptr 我正在創建一個游戲,並且正在使用unique_ptrvector來存儲我的游戲狀態。

這是我的矢量代碼:

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM