Curyous
Curyous

Reputation: 8866

How to return a shared_ptr of this to the object that owns it?

The similar questions here all seem to use boost, which I'm not using.

What I'm trying to do is demonstrated by the following:

In the "owner":

std::shared_ptr<State> m_state;

m_state = make_shared<State>(param);

m_state = m_state->SomeVirtualFunction();    // The original m_state object gets destroyed

In the "owned":

std::shared_ptr<State> State::SomeVirtualFunction() {
    return std:shared_ptr<State>(this);
}

In Visual C++ in MSVS 2012, the owned object gets destroyed. How can I keep it alive?

Upvotes: 5

Views: 4336

Answers (2)

ecatmur
ecatmur

Reputation: 157334

You need to inherit from std::enable_shared_from_this; see What is the usefulness of `enable_shared_from_this`?. std::enable_shared_from_this equips your type with a member function shared_from_this that you call instead of std::shared_ptr<State>(this):

std::shared_ptr<State> State::SomeVirtualFunction() {
    return shared_from_this();
}

Prior to C++11 (or Boost, which is where C++11 got enable_shared_from_this from), and assuming that you have a shared_ptr implementation that doesn't provide enable_shared_from_this, you can do this manually by giving State a weak_ptr to itself that it can convert to a shared_ptr when it needs to:

class State {
    ...
    std::weak_ptr<State> weak_self;
};

m_state = make_shared<State>(param);
m_state->weak_self = m_state;

std::shared_ptr<State> State::SomeVirtualFunction() {
    return weak_self.lock()
}

Upvotes: 9

AProgrammer
AProgrammer

Reputation: 52284

State should inherit from std::enable_shared_from_this<State> and State::SomeVirtualFunction() should be

return shared_from_this();

Note that you must not change the code in the owner.

Upvotes: 1

Related Questions