Say I have :
class Foo
{
public:
Foo(std::function< void(std::shared_ptr< Foo >) > callback);
void shareMyFoo()
{
callback(std::make_shared< Foo >(this));
}
....
};
When shareMyFoo()
is invoked, someone will have a chance to copy the shared pointer. Unfortunately, as it will die --that is, its ref counter dropped to 0--, it will kill my Foo. I would like to prevent Foo
from being suicided.
I thought of having a field std::shared_ptr< Foo > sharedSelf_
in Foo
, that I would initialize in the constructor, but that's cheap as well.
More generally, imagine I instantiate and store a pointer to an object in a shared pointer, (auto foo = std::make_shared< Foo >()
for instance), and later the instance wants to pass itself as a shared pointer. How can I update the ref counter globally ?
N.B. : I want/need to preserve my signatures/my shared_ptr arguments over my application.
You have to inherit from std::enable_shared_from_this
(n3242 §20.7.2.4).
auto p = (new Foo) -> shared_from_this ();