Boost logo

Boost :

From: Andreas Huber (ahd6974-spamgroupstrap_at_[hidden])
Date: 2004-10-23 19:03:04


Hi Colin

colin.rafferty_at_[hidden] wrote:
>>> No, the constructor is implicit by design. Do you have a case where
>>> the implicit constructor causes problems?
>
>> Sure, this is the same problem as for shared_ptr<>.
>
>> extern void foo(const intrusive_ptr<Bar>&);
>
>> void baz()
>> {
>> Bar* bar = new Bar;
>> foo(bar); // oops!
>> delete bar;
>> }

For this to work, intrusive_ptr_add_ref and intrusive_ptr_release
functions accepting a Bar * (or a base class pointer) must exist. That
is, someone already decided that *all* heap-allocated Bar objects will
be intrusively reference-counted. Creating a heap-allocated Bar object
without immediately passing the pointer to the intrusive_ptr constructor
is dangerous. Is there a reason why you do that?

I can't speak for Peter but I believe he made intrusive_ptr constructor
non-explicit because there is no room for abuse as long as you follow
the best practices he describes. The same isn't true for heap-allocated
objects pointed to by a shared_ptr:

extern void foo( const shared_ptr< Bar > & );

void baz()
{
  shared_ptr< Bar > pBar = new Bar();
  foo( pBar.get() ); // compiler error here because of explicit ctor
}

With a non-explicit ctor, the last line would compile just fine but
eventually lead to a double-delete. With intrusive_ptr this isn't a
problem at all, hence the non-explicit constructor there.

Regards,

-- 
Andreas Huber
When replying by private email, please remove the words spam and trap
from the address shown in the header. 

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