What's a good C++ design pattern to get an owning shared_ptr
from inside a member function?
Inside my function I need to store a shared_ptr
to this
away and retrieve later -- in another scope. This naïve approach doesn't work:
void Foo::doSomething(shared_ptr<Bar> bar)
{
bar->setFoo(make_shared<Foo>(this));
}
void Bar::setFoo(shared_ptr<Foo> foo)
{
myFoo.reset(foo);
}
Now if I do
shared_ptr<Foo> foo(new Foo());
shared_ptr<Bar> bar(new Bar());
foo->doSomething(bar);
there's no way that I can later know if bar->myFoo
is still valid.
The problem is that I'm creating a 2nd shared_ptr
to the same Foo
instance. But there's no way for me to access the shared_ptr
from within the function because I only have this
.
(Obviously the actual setup is more complex than this simple example)
You are looking for std::enable_shared_from_this and std::enable_shared_from_this::shared_from_this