2010-07-30 59 views
4

我正在学习使用智能增强指针,但我对某些情况有点困惑。我们假设我正在实现一个状态机,每个状态通过一个更新方法来实现。 每个国家可以返回其自身或创建一个新的状态对象:使用智能指针与“这个”

struct state 
{ 
    virtual state* update() = 0; // The point: I want to return a smart pointer here 
}; 

struct stateA : public state 
{ 
    virtual state* update() { return this; } 
}; 

struct stateB : public state 
{ 
    virtual state* update() { if(some condition) return new stateA() else return this; } 

};

状态机循环应该是这样的:

while(true) 
    current_state = current_state->update(); 

你能翻译这段代码使用boost智能指针?当涉及到“返回这个”部分时,我有点困惑,因为我不知道该怎么做。 基本上我觉得返回类似“return boost :: shared_ptr(this)”的东西是没用的,因为它不安全。 我该怎么办?

回答

6

你必须让你的类继承boost::enable_shared_from_this<>。看看Boost的例子here