问题描述
我想为此语法实现FSM/下推式自动机"解析器:,该解析器已被词汇化"为有限状态机解析器
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
我有以下内容:
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 );
}
使用B
的event()
(在许多if-elseif之后)return m_parent->deleteDaughter()
.我知道这很腥(并且崩溃了),但是我需要一种方法来从女儿State
返回父亲State
,并确保女儿State
没有泄漏.
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.
我的事件循环如下:
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.
我了解关于此主题的书籍很多,但我不是计算机科学家/程序员,我想学习自己做到这一点(当然,在SO的所有友好人员的帮助下).如果概念不清楚,请询问.谢谢!
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!
推荐答案
仍然可以发表您的看法,但是我想出了如何优雅地处理所有问题的方法:
Feel free to still post your take on this, but I have figured out how to handle everything gracefully:
首先:我的事件循环将保留指向最后创建的State*
的指针.
First: my event loop will keep a pointer to the last State*
created.
第二个:每个State
都有一个指向父级State
的指针,该指针在构造函数中初始化,默认为0(如果用于第一个State*
以外的任何内容,则发生内存泄漏);这保证了任何国家都不会超出范围.
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.
第三项:State* endOfState()
函数正是这样做的(我为此感到特别自豪.
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;
}
在子类的event()
中调用此方法时,它将正确删除自身,并返回父指针(在梯形图中向上移动).
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:为了公平起见,灵感来自 http://www .codeguru.com/forum/showthread.php?t = 179284
PS: for all fairness, inspiration was stolen from http://www.codeguru.com/forum/showthread.php?t=179284
这篇关于C ++ FSM设计和所有权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!