tags:

views:

85

answers:

1

Hi,

I would like to implement a FSM/"pushdown automaton" parser for this syntax: http://stackoverflow.com/questions/3025293/c-general-parser-with-scopes-and-conditionals which has already been "lexed" into http://stackoverflow.com/questions/3085070/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!

A: 

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

rubenvb