Skip to content

Entry and Exit Actions

Sergei Fedorov edited this page Nov 20, 2016 · 2 revisions

Any state or state machine can define handling of state enter and exit. Functions are passed references to event that triggered state entry or exit and reference to the state machine that contains the state. Entry action is passed an rvalue reference to the event if process_event was called with rvalue reference to the event or the transition is caused by an event that was queued or deferred.

Generic entry/exit actions (catch all):

struct my_state : state<my_state> {
    template < typename Event, typename FSM >
    void
    on_enter(Event&& evt, FSM& fsm) 
    {
        ::std::cerr << "my_state enter\n";
    }
    template < typename Event, typename FSM >
    void
    on_exit(Event const& evt, FSM& fsm)
    {
        ::std::cerr << "my_state exit\n";
    }
};

A state can define any number of entry/exit actions to handle every event separately. Entry/exit actions are optional and when defining an action handling some specific event entry/exit one doesn't have to define catch all actions for other possible events. Entry/exit actions can be const-qualified.

on_enter and on_exit vs. constructor and destructor

The main reason in using a pair of member functions is that a class can have only one destructor and therefore cannot handle exiting on different events. Also it makes the implementation much simpler and more efficient. Technically there exist an instance of every state in the state machine at all the times, and the states are constructed when the outermost state machine is constructed. States that do not have history will be reconstructed after entering next state and assigned to states contained in state machines. If move assignment is available it will be used.

Clone this wiki locally