C++ FSM design and ownership

后端 未结 1 719
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 17:52

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

相关标签:
1条回答
  • 2021-01-15 18:21

    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

    0 讨论(0)
提交回复
热议问题