C++ FSM design and ownership

倖福魔咒の 提交于 2019-12-20 03:13:03

问题


I would like to implement a FSM/"pushdown automaton" parser for this syntax: parser with scopes and conditionals which has already been "lexed" into Finite State Machine parser

I have the following:

class State
{
public:
    virtual State* event( const string &token );
    State* deleteDaughter();
private:
    A* m_parent;
    A* m_daughter;
}
class SomeState : public State
{
public:
    State* event( const std::string &token );
}

With B's event() doing (after many if-elseif's) return m_parent->deleteDaughter(). I know this is fishy (and it crashes), but I need way to return the parent State from the daughter State and make sure the daughter State isn't leaked.

My event loop looks like this:

while( somestringstream >> token )
    state = state->event();

Before you scold the design and last piece of code, I tried extending a much too simple example from here, which seems pretty ok. I am moving the decision part to the states themselves, for clarity and brevity.

I understand there's loads of books on this subject, but I'm no computer scientist/programmer and I want to learn to do this myself (of course, with the help of all the friendly people at SO). If the concept isn't clear, please ask. Thanks!


回答1:


Feel free to still post your take on this, but I have figured out how to handle everything gracefully:

First: my event loop will keep a pointer to the last State* created.

Second: Each State has a pointer to the parent State, initialized in the constructor, defaulting to 0 (memory leak if used for anything but the first State*); this guarantees that no State will go out of scope.

Third: State* endOfState() function which does exactly this (and I'm particularly proud of this.

State* State::endOfState()
{
    State* parent = m_parent; // keep member pointer after suicide
    delete this;
    return parent;
}

When this is called from within a subclass's event(), it will properly delete itself, and return the parent pointer (going one up in the ladder).

If this still contains a leak, please inform me. If the solution is not clear, please ask :)

PS: for all fairness, inspiration was stolen from http://www.codeguru.com/forum/showthread.php?t=179284



来源:https://stackoverflow.com/questions/3176110/c-fsm-design-and-ownership

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!