Boost smart pointers
When开发者_运维知识库 should intrusive_ptr be used instead of shared_ptr ?
When you already have a reference counter stored inside the object you're pointing to.
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.
What Nick said. One real-life example is managing COM pointers.
精彩评论