Convert c++98 code to new c++17 code when using std::vector of pointers

89 views Asked by At

i dont what to manage or less as i can manage raw pointers note in the example i have to delete the object before removeing it from the vector i want to avoid it it here and later what will be good case to convert this code to using unique_ptr or shared_ptr

class GameState
{
    public:
        virtual bool onEnter() = 0;
        virtual bool onExit() = 0;
        virtual std::string getStateID() const = 0;
};

class MenuState : GameState
{
        public:
             MenuState(){};
             virtual ~MenuState(){};             
             bool onEnter(){};
             bool onExit(){};
             std::string getStateID() const;
        private:
             static const std::string s_menuId;

};

class StateMechine
{
    
    public:
        void pushState(GameState* pState)
        {
            m_gameStates.pop_back(pState);
            m_gameStates.back()->onEnter();
        }

        void changeState(GameState* pState)
        {
            if(!m_gameStates.empty())
            {
                if(m_gameStates.back()->onExit())
                {
                    delete m_gameStates.back();
                    m_gameStates.pop_back();
                }
            }
        }

         
    private:
        std::vector<GameState*> m_gameStates;
}

int main(int argc ,char** argv)
{
    GameState *gs  = new MenuState();
    StateMechine sm;
    sm.pushState(gs);
    sm.changeState(gs);
}
1

There are 1 answers

0
Johann Schwarze On

The std::vector<GameState*> can be replaced with a std::vector<std::unique_ptr<GameState>>. That way a call to m_gameStates.pop_back() will delete the corresponding object.

class StateMechine
{
    
    public:
        void pushState(std::unique_ptr<GameState> pState)
        {
            m_gameStates.push_back(std::move(pState));
            m_gameStates.back()->onEnter();
        }

        void changeState()
        {
            if(!m_gameStates.empty())
            {
                if(m_gameStates.back()->onExit())
                {
                    m_gameStates.pop_back();
                }
            }
        }

         
    private:
        std::vector<std::unique_ptr<GameState>> m_gameStates;
};

int main(int argc ,char** argv)
{
    StateMechine sm;
    sm.pushState(std::make_unique<MenuState>());
    sm.changeState();
}