Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
Emiliano Avatar asked Dec 02 '22 04:12

Emiliano


1 Answers

You may want to look at enable_shared_from_this, which is there for specificly solving problems similar to yours.

like image 79
hkaiser Avatar answered Dec 26 '22 19:12

hkaiser