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?
You need to inherit from
std::enable_shared_from_this; see What is the usefulness of `enable_shared_from_this`?.std::enable_shared_from_thisequips your type with a member functionshared_from_thisthat you call instead ofstd::shared_ptr<State>(this):Prior to C++11 (or Boost, which is where C++11 got
enable_shared_from_thisfrom), and assuming that you have ashared_ptrimplementation that doesn’t provideenable_shared_from_this, you can do this manually by givingStateaweak_ptrto itself that it can convert to ashared_ptrwhen it needs to: