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?
You may want to look at enable_shared_from_this
, which is there for specificly solving problems similar to yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With