Possible duplicate:
C ++: delete this?
I am trying to create a state management system for a game.
The problem with my current design is that when I switch states, the old state is deleted before the control switches to the new state.
The following is simplified code for my code:
class StateManager; class State { public: virtual void update(StateManager &manager)= 0; virtual ~State(){} }; class StateManager { public: void setState(std::unique_ptr<State> && newState ) { currentState = std::move(newState); } std::unique_ptr<State> currentState; void run() { currentState->update(*this); } };
Note that if the State object calls StateManager :: setState in the update method, there will be a period of time when the member function is called on the newly destroyed object.
A full example of this behavior is at http://ideone.com/WHLzJL . Notice how the destructor for FirstState is called before returning FirstState :: update.
Is this behavior undefined in C ++? If so, how can I change my design?
source share