2

I have a std::stack which has some pointers inside:

std::stack<State*> m_states;

When I initialize my program, I call new to push an item onto the stack (it must be a pointer because I will use polymorphic types).

Is this the correct way of deleting with all the stuff?

Here is where I call new (GameState and MenuStatesare classes inherited fromState`):

m_states.push(new GameState());
m_states.push(new MenuState());

And this is what I have in the destructor of the whole App class:

while (!m_states.empty())
{
    delete m_states.top(); // (*)
    m_states.pop();
}

Should I only call (*), or do I need to pop() as well?

1
  • 4
    Better to use a unique_ptr and not have to deal with cleanup at all. Commented Nov 20, 2021 at 22:15

1 Answer 1

4

Should I only call (*) or do I need to pop as well?

Well, if you don't call pop() in the while loop, then how will that loop ever end? In other words, how will the condition, !m_states.empty() ever become false?

There are other container types (like std::vector) where you could just run through each member, deleting the pointed-to object, and then clear the container, but you can't do that with the std::stack container. That is to say, there is no [] operator for a stack – you can only access the top element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.