Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost intrusive pointer

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

"Every new intrusive_ptr instance increments the reference count by using an unqualified call to the function intrusive_ptr_add_ref, passing it the pointer as an argument. Similarly, when an intrusive_ptr is destroyed, it calls intrusive_ptr_release; 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.

like image 909
Benjamin Larsen Avatar asked Oct 19 '16 17:10

Benjamin Larsen


People also ask

What is boost intrusive_ ptr?

Introduction. The intrusive_ptr class template stores a pointer to an object with an embedded reference count. Every new intrusive_ptr instance increments the reference count by using an unqualified call to the function intrusive_ptr_add_ref , passing it the pointer as an argument.

Why intrusive_ ptr?

The main reasons to use intrusive_ptr are: Some existing frameworks or OSes provide objects with embedded reference counts; The memory footprint of intrusive_ptr is the same as the corresponding raw pointer; intrusive_ptr<T> can be constructed from an arbitrary raw pointer of type T *.


1 Answers

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.

like image 159
Angew is no longer proud of SO Avatar answered Sep 28 '22 13:09

Angew is no longer proud of SO