4

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?

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
Curyous
  • 8,716
  • 15
  • 58
  • 83
  • 2
    `std::shared_ptr` came from boost, so the answers to the questions using boost will most likely be applicable to your problem. – JoeG Aug 21 '12 at 09:41

2 Answers2

8

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()
}
Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

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.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143