Benjamin Larsen Benjamin Larsen - 2 months ago 25
C++ Question

Boost intrusive pointer

I'm a little confused about boost's intrusive pointer. The definition says:

"Every new
instance increments the reference count by
using an unqualified call to the function
passing it the pointer as an argument. Similarly, when an
is destroyed, it calls
; this
function is responsible for destroying the object when its reference
count drops to zero. The user is expected to provide suitable
definitions of these two functions. "

Does this mean that I HAVE TO implement these methods, or that I CAN do it? The point is, that we're using it because a function requires an intrusive pointer. We've used shared pointer the other places, so were just worried if the pointer is managed, and is going to be deleted when theres no more references to it.


You have to provide these functions. This is how boost::intrusive_ptr operates.

Let's compare it with boost::shared_ptr. shared_ptr manages the reference count itself in the control block associated with the pointee. Creating a shared_ptr increments the refcount. Destroying a shared_ptr decrements the refcount. When the refcount goes to 0, the pointee is destroyed.

intrusive_ptr works in exactly the same way, but does not manage the reference count itself. It just signals to its client "now the refcount must be incremented" and "now the refcount must be decremented." It does that by calling the two functions mentioned, intrusive_ptr_add_ref and intrusive_ptr_release. If you do not define them, you will get a compilation error.

Think of these functions as the interface to the reference counter. Using intrusive_ptr indicates that the refcount is managed somewhere outside the pointer (usually in the pointee itself), and the pointer just intrudes on that refcount, using it for its purposes.