Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-04-10 15:59:53


Ulrich Eckhardt wrote:
> On Thursday 06 April 2006 07:50, I wrote:
>> http://boost.org/libs/smart_ptr/intrusive_ptr.html says:
>> "As a general rule, if it isn't obvious whether intrusive_ptr better
>> fits your needs than shared_ptr, try a shared_ptr-based design
>> first."
>>
>> I wonder why? Embedding the refcounter into the object seems to me
>> much more natural and performant than adding another free-store
>> allocation which shared_ptr requires.
>
> Nobody wants to even take a guess why? I seriously don't know why one
> would use shared_ptr by default - I'm aware that some people might
> want the additional features, but that doesn't justify such an advise.

One reason for the "try shared_ptr first" recommendation is that while
intrusive_ptr's advantages are usually obvious to developers, its
disadvantages and shared_ptr's advantages are not. They became evident at a
later date.

intrusive_ptr is obviously the right choice when (1) shared_ptr's overhead
is unacceptable, (2) when the design often needs to convert raw pointers
into smart pointers, (3) when the underlying API already uses intrusive
counting.

And, if you pay attention:

>> "As a general rule, if it isn't obvious whether intrusive_ptr better
>> fits your needs than shared_ptr, try a shared_ptr-based design
>> first."

you'll see that the recommendation is for the cases where it isn't obvious
whether intrusive_ptr is a better choice.

Since most programmers are naturally biased in favor of intrusive_ptr, this
just balances the things out.

The main disadvantage of intrusive_ptr is that you need to know about the
reference count, which usually means no incomplete classes, and virtual
inheritance from a non-abstract class containing data members in every
interface. This is manageable, but if you can live without it, you'll
certainly want to. Also, weak pointers are cool. Really. :-)


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk