Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't intrusive_ptr and shared_ptr be used with boost::intrusive containers?

The boost::intrusive documentation describes how you can use smart pointers with intrusive containers but then says you can't use the smart pointers you'd be most likely to use, "It must have the same ownership semantics as a raw pointer. This means that resource management smart pointers (like boost::shared_ptr) can't be used."

Why is this? I can't think of any obvious reason they should be prohibited. What exactly would break? Intrusive containers don't manage allocation of the items inside them anyway. In my case I'd like to use intrusive_ptr, but I don't see any reason why shared_ptr shouldn't work either.

Edit: To be clear, I mean for the hook pointer (e.g. the next pointer in an intrusive singly linked list) to be a smart pointer.

like image 308
Joseph Garvin Avatar asked Dec 14 '12 01:12

Joseph Garvin


People also ask

What is boost intrusive_ptr?

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

Perhaps there's a clue in the documentation for boost::intrusive::slist where it states that with the default configuration, slist is stored as a circular list, which precludes using shared_ptr/intrusive_ptr and friends, because you'd have a reference cycle.

It's still annoying that one part of boost doesn't work properly with another; I guess the only the workaround would be to use something like intrusive_ptr and manually bump the reference count when you add an object to the container, and decrement it when you remove it. (This rules out shared_ptr, because you can't adjust its reference count directly.)

like image 184
Nick Hutchinson Avatar answered Oct 24 '22 04:10

Nick Hutchinson