Search code examples
c++pointersmemorynew-operator

Do I need to free the memory in this case somehow?


I have a pointer State *state; which is a class that other states inherit from. And I do state = new GameState; Do I need to free the memory here somehow, if I change what the object state points to from GameState to something else?


Solution

  • If what you mean is that State* state does NOT own the object you will need to do something like this:

        // create states
        State* game_state = new GameState();
        State* menu_state = new MenuState();
        // set current state
        State* state = game_state;
        // ... do somethings ...
    
        // delete states
        delete game_state;
        game_state = nullptr;
        delete menu_state;
        menu_state = nullptr;
        state = nullptr;
    

    If you want to write modern code use:

        // create states
        auto game_state = make_unique<GameState>();
        auto menu_state = make_unique<MenuState>();
        // set current state
        State* state = game_state.get();
        // ... do somethings ...
    
        // no need to delete states
        state = nullptr;
    

    You could also use a combination of shared_ptr's and weak_ptr's.

    If not using smart pointers, you need to call delete on whatever owns the object.


    If State* state DOES own the object then you need to do:

    // create current state
    State* state = new GameState();
    // ... do somethings ...
    
    // switch state
    delete state;
    state = new MenuState();
    
    // ... do somethings ...
    
    // delete state
    delete state;
    state = nullptr;
    

    And with smart pointers:

    // create current state
    unique_ptr<State> state = make_unique<GameState>();
    // ... do somethings ...
    
    // switch state (old state automatically deleted)
    state = make_unique<MenuState>();
    // ... do somethings ...
    
    // delete state
    state = nullptr;