Is this behavior undefined so that the object is deleted before its member function returns?

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?

+4
source share
3 answers

No, everything is fine, if you are careful: https://isocpp.org/wiki/faq/freestore-mgmt#delete-this

+7
source

There are no problems, and this is the last thing you do in this function. ( delete this is a common idiom.) However, in this particular case, I usually preferred that State::update return a new State (which could be this ). The code that calls it in the StateManager simply assigns it to a pointer.

In this case, be careful with the semantics of smart pointers. I did this using an invariant generic pointer, but I suspect that most modern smart pointers will not work here. On the other hand, you really don't need a smart pointer, so why add complications.

+2
source

As far as I know, the main effect is that this becomes a dangling pointer, so accessing fields, calling virtual methods or executing something like dynamic_cast<T*>(this) , which uses information like runtime, will lead to undefined.

0
source

Source: https://habr.com/ru/post/1443756/


All Articles