C++ 将智能指针与“一起使用”;这";

C++ 将智能指针与“一起使用”;这";,c++,boost,boost-smart-ptr,C++,Boost,Boost Smart Ptr,我正在学习boost智能指针的使用,但我对一些情况有点困惑。 假设我正在实现一个状态机,其中每个状态都由一个更新方法实现。 每个状态都可以返回自身或创建新的状态对象: struct state { virtual state* update() = 0; // The point: I want to return a smart pointer here }; struct stateA : public state { virtual state* update() {

我正在学习boost智能指针的使用,但我对一些情况有点困惑。 假设我正在实现一个状态机,其中每个状态都由一个更新方法实现。 每个状态都可以返回自身或创建新的状态对象:

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);”的内容是没有用的,因为这样不安全。
我该怎么办?

您可能想看看,这是专门用来解决类似于您的问题的。

您必须使您的类继承自
boost::enable\u shared\u from\u this
。看看Boost的例子