Possible Duplicate:
C++: Delete this?
I am trying to create a system to manage states for a game.
The issue with my current design is that when I switch states, the old state is deleted before control switches over to the new state.
The following is a simplified version of 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);
}
};
Notice how if a State object calls StateManager::setState while in the update method, there will be a period of time when a member function is being called on an object that has just been destroyed.
A complete example of this behavior is at http://ideone.com/WHLzJL. Note how the destructor for FirstState is called before FirstState::update returns.
Is this undefined behavior in C++? If so, how should I change my design?