简体   繁体   中英

using smart pointers with “this”

I'm learning the use of boost smart pointers but I'm a bit confused about a few situations. Let's say I'm implementing a state machine where each state is implemented by a single update method. Each state could return itself or create a new state object:

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; }

};

The state machine loop would look like this:

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

Could you translate this code to use boost smart pointers? I'm a bit confused when it comes to the "return this" part because I don't know what to do. Basically I think it's useless to return something like "return boost::shared_ptr(this);" because it's not safe. What should I do?

您可能需要查看enable_shared_from_this ,它可以解决与您类似的问题。

You have to make your classes inherit from boost::enable_shared_from_this<> . Check out Boost's example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM