如何将原始指针向量转换为唯一指针向量?

How to turn vector of raw pointers into a vector of unique pointers?

#include <vector>

enum ListOfGameStates
{
    // List of game states
};

class GameState()
{
    public:
        GameStates(); // Initializes protected (global) variables
        virtual ListOfGameStates run() = 0;
    protected:
        // Heavyweigh resource managers containing all resources and other global vars
}

class GameStateManager()
{
    public:
        GameStateManager();  // Creates all game states
        ~GameStateManager(); // Deletes all game states
        void run();          // Switches from one state to another state
    private:
        // A vector of raw pointers to game states. GameState is a base class.
        std::vector<GameState*> game_states_container;
}

我想摆脱原始指针,这样我就不用担心异常和清理问题。是否有简单的解决方案(我是一个非常愚蠢的青少年)或者不值得吗?谢谢!

只需将向量更改为:

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

并删除析构函数中的任何 delete。事实上,你可以完全摆脱析构函数,除非它有其他工作要做。

unique_ptr 不可复制但可移动,因此值得了解 C++11 移动语义。当你想添加一个 unique_ptr 到你的容器时,你可以使用 push_back 提供你传递一个临时的,例如函数的 return 值:

game_states_container.push_back(createGameState());
game_states_container.push_back(std::make_unique<GameStateA>());  // C++14

或者,如果您有一个本地 unique_ptr 变量,您可以使用 std::move 将其移动到向量中:

std::unique_ptr<GameState> game_state = std::make_unique<GameStateA>();  // C++14
// auto game_state = std::unique_ptr<GameState>(new GameStateA);  // C++11
...
game_states_container.push_back(std::move(game_state));

最好在 new 后立即将原始指针放入 unique_ptr(或者最好使用 std::make_unique)。否则,如果在 unique_ptr 中的分配和包装之间抛出异常,则会发生内存泄漏。

它与 unique_ptr 无关,但你的 GameState class should have a virtual destructor.

Live demo