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 from
State`):
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?
CodePudding user response:
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.