Emi*_*ano 4 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() { return this; }
};
struct stateB : public state
{
virtual state* update() { if(some condition) return new stateA() else return this; }
Run Code Online (Sandbox Code Playgroud)
};
状态机循环看起来像这样:
while(true)
current_state = current_state->update();
Run Code Online (Sandbox Code Playgroud)
你能翻译这段代码来使用boost智能指针吗?当谈到"返回这个"部分时,我有点困惑,因为我不知道该怎么做.基本上我觉得返回像"return boost :: shared_ptr(this);"这样的东西是没用的.因为它不安全 我该怎么办?