Boost logo

Boost Users :

From: Nat Goodspeed (ngoodspeed_at_[hidden])
Date: 2005-01-31 21:58:17


> -----Original Message-----
> From: boost-users-bounces_at_[hidden] [mailto:boost-users-
> bounces_at_[hidden]] On Behalf Of Brian Neal
> Sent: Monday, January 31, 2005 7:34 PM
> To: boost-users_at_[hidden]
> Subject: [Boost-users] Rationale for intrusive_ptr?
>
> Hi, I need some help understanding when and why you
> would want to use intrusive_ptr. Does someone have an
> example? I didn't get much out of the current
> documentation for it. Thank you.

[Nat] Consider:

class MyClass;

void some_func(const boost::shared_ptr<MyClass>& ptr);

class MyClass
{
public:
    void process()
    {
        // BAD THINGS HAPPEN!
        some_func(boost::shared_ptr<MyClass>(this));
    }
};

In our current project, we've been bitten more than once :-( by
situations that are analogous but less obvious. Inside a member
function, you don't have a shared_ptr<MyClass>, you only have a dumb
MyClass* 'this' pointer. But if MyClass is managed with smart pointers,
you probably have processing functions that accept only a smart pointer
to MyClass. A natural-looking data conversion is easy to code and makes
the compiler happy.

What happens, though, is that when you instantiate a new
shared_ptr<MyClass> from your dumb 'this' pointer, it gets a whole new
refcount object! In the example above, the temporary shared_ptr<> goes
away as you're about to exit MyClass::process() -- which makes its
spurious refcount go to 0 -- which deletes the MyClass instance in
question, even though there are probably still existing
shared_ptr<MyClass> references to the same instance lying around! (e.g.
the one with which you called the process() method)

We now use intrusive_ptr almost exclusively (vs. shared_ptr). We limit
its intrusiveness by deriving all subject classes from an intrusive_base
we wrote, which contains the refcount we use and a couple of methods.
This practice has cut down considerably on bizarre crashes.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net