codentary
codentary

Reputation: 1175

Boost statechart `state context` is null

I have a small sm with just one state for now.
I want from within the state, to access some data that is received and stored by the sm on construction:

struct data {
    std::string m_ip;
    data(const char* ip)
        : m_ip(ip)
    {
    }
};

namespace sc = boost::statechart;

struct s1;
struct sm : sc::state_machine<sm, s1> {
    data* m_data;
    sm(data* d)
        : m_data { d }
    {
    }
};

struct s1 : sc::simple_state<s1, sm> {
    s1()
    {
        std::cout << context<sm>().m_data->m_ip; // assertion
    }
};

int main()
{
    data _data("192.168.1.1");
    sm _sm(&_data);
    _sm.initiate();

    return 0;
}

When I run this, I get the following error:

test: /usr/include/boost/statechart/simple_state.hpp:682: static OtherContext& boost::statechart::simple_state<MostDerived, Context, InnerInitial, historyMode>::context_impl_other_context::context_impl(State&) [with OtherContext = sm; State = boost::statechart::simple_state<s1, sm>; MostDerived = s1; Context = sm; InnerInitial = boost::mpl::list<mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>; boost::statechart::history_mode historyMode = (boost::statechart::history_mode)0]: Assertion `get_pointer( stt.pContext_ ) != 0' failed.

I don't understand why the context pointer is null.

Upvotes: 2

Views: 297

Answers (1)

codentary
codentary

Reputation: 1175

I found my answer here.
It was staring me in the face, from the comment above the assertion:

// This assert fails when an attempt is made to access an outer 
// context from a constructor of a state that is *not* a subtype of
// state<>. To correct this, derive from state<> instead of
// simple_state<>.

Not sure if this should be marked as duplicate as it is the same issue, but triggered a bit differently (the context is an outer state, not the state machine itself, as in my case).

Upvotes: 2

Related Questions