【发布时间】:2014-02-20 09:47:35
【问题描述】:
我已经实现了一个继承 boost::statechart 的状态机。当我调用fsm.process_event( some_event() ) 哪个反应预计会引发异常时,结果证明在我使用try-catch 块处理异常后,我的状态机实例fsm 被终止。也就是说,fsm.terminated() 返回true。在某些情况下,我不希望它被终止。就像我希望状态机抛出异常以通知调用者 fsm.process_event( irrelevant_event() ) 的未处理事件并在事件状态之前保持其当前状态。
简而言之 - 如何防止 boost::statechart 在引发异常后终止并保持其在异常状态之前的状态?
示例代码:
namespace sc = boost::statechart;
class State;
struct some_event : public sc::event<some_event> { };
class FSM
: public sc::state_machine< FSM, State, std::allocator<void>, sc::exception_translator<> >
{
public:
FSM()
{
cout<<"FSM::FSM()"<<endl;
}
virtual ~FSM()
{
cout<<"FSM::~FSM()"<<endl;
}
};
class State : public sc::simple_state< State, FSM >
{
public:
State()
{
cout<<"State::State()"<<endl;
}
virtual ~State()
{
cout<<"State::~State()"<<endl;
}
typedef boost::mpl::list<
sc::custom_reaction< some_event >,
sc::custom_reaction< sc::exception_thrown >
> reactions;
sc::result react( const some_event & e)
{
cout<<"State::react( const some_event &)"<<endl;
throw std::exception();
return this->discard_event();
}
sc::result react( const sc::exception_thrown & e)
{
cout<<"State::react( const sc::exception_thrown &)"<<endl;
throw;
return this->discard_event();
}
};
int main()
{
FSM fsm;
fsm.initiate();
try
{
fsm.process_event(some_event());
}
catch(...)
{
cout<<"Exception caught"<<endl;
}
if(fsm.terminated())
{
cout<<"fsm2 is TERMINATED"<<endl;
}
else
{
cout<<"fsm2 is RUNNING"<<endl;
}
return 0;
}
代码输出:
FSM::FSM()
State::State()
State::react( const some_event &)
State::react( const sc::exception_thrown &)
State::~State()
Exception caught
fsm2 is TERMINATED
我希望它输出:
FSM::FSM()
State::State()
State::react( const some_event &)
State::react( const sc::exception_thrown &)
State::~State()
Exception caught
fsm2 is RUNNING
【问题讨论】:
标签: c++ boost-statechart