I am making extensive use of boost:shared_ptr
in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr
. Unfortunately this means that I can't pass this
into any function that takes a shared_ptr
. Consider this code:
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::someFunction()
{
bar(this);
}
There are two problems here. First, this won't compile because the T* constructor for shared_ptr
is explicit. Second, if I force it to build with bar(boost::shared_ptr<Foo>(this))
I will have created a second shared pointer to my object that will eventually lead to a double-delete.
This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?
See Question&Answers more detail:os