Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost smart pointers

Tags:

c++

boost

When should intrusive_ptr be used instead of shared_ptr ?

like image 269
Adrian Avatar asked Mar 04 '11 16:03

Adrian


2 Answers

When you already have a reference counter stored inside the object you're pointing to.

like image 128
Nick Avatar answered Oct 28 '22 15:10

Nick


From Beyond the C++ Standard Library: An Introduction to Boost By Björn Karlsson

In most situations, you should not use boost::intrusive_ptr, because the functionality of shared ownership is readily available in boost::shared_ptr, and a non-intrusive smart pointer is more flexible than an intrusive smart pointer. However, there are times when one needs an intrusive reference count, perhaps for legacy code or for integration with third-party classes. When the need arises, intrusive_ptr fits the bill, with the same semantics as the other Boost smart pointer classes.

By using another of the Boost smart pointers, you ensure a consistent interface for all smart pointer needs, be they intrusive or not. The reference count must be provided by the classes that are used with intrusive_ptr. intrusive_ptr manages the reference count by making unqualified calls to two functions, intrusive_ptr_add_ref and intrusive_ptr_release; these functions must properly manipulate the intrusive reference count for intrusive_ptrs to work correctly. For all cases where a reference count already exists in the types that are to be used with intrusive_ptr, enabling support for intrusive_ ptr is as easy as implementing those two functions.

Use intrusive_ptr when

  • You need to treat this as a smart pointer.
  • There is existing code that uses or provides an intrusive reference count.
  • It is imperative that the size of the smart pointer equals the size of a raw pointer.
like image 43
DumbCoder Avatar answered Oct 28 '22 14:10

DumbCoder