Boost logo

Boost :

From: colin.rafferty_at_[hidden]
Date: 2004-10-25 08:03:26


"Andreas Huber" <ahd6974-spamgroupstrap_at_[hidden]> wrote:
> 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<>.

>>> [elided example double-delete]

> 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 agree. However, sometimes I don't have control over my base classes
(or at least, they can surprise me). Imagine the case where a 3rd
party library doesn't have a very good interface:

    class Base;
    extern void foo(Base*);

I create a derived class and use it cleanly.

    class Derived : public Base { /* ... */ };

    void baz()
    {
        scoped_ptr<Derived> dptr(new Derived);
        foo(dptr.get());
    }

In the next version of the library, someone has talked to the
developers, and they've made it safer:

    extern void intrusive_ptr_add_ref(Base* p);
    extern void intrusive_ptr_release(Base* p);

    extern void foo(const intrusive_ptr<Base>&);

My existing code in `baz' still compiles, but now I have the
double-delete problem.

> 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.

I agree that an intrusive_ptr is less likely to get bitten by the
implicit constructor than a shared_ptr. However, I can see three
reasons why it should still be explicit:

1. It is still potentially dangerous.

2. It is consistant with every other pointer class in boost and std.

3. There is no time when someone would actually want the implicit
   conversion, so there's no disadvantage.

This hasn't bitten me (yet), but I imagine that's only because
intrusive_ptr is such a new addition.

-- 
Colin

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