(1)boost中的智能指针
Boost提供了下面几种智能指针(Smart Pointers to boost your code):
将原文部分放上来,防止笔者翻译水平有限,影响大家阅读,请对照内容:
share_ptr
scope_ptr
intrusive_ptr
weak_ptr
share_array
scope_array
(2)share_ptr引入
首先,我们通过例子来了解这个智能指针,
1: void Sample_Shared() 2: { 3: // (A) create a new CSample instance with one reference 4: boost::shared_ptr
在代码块(A)中,在堆中创建一个CSample对象,通过绑定share_ptr指针到mySample,如下图示:
(B)中我们通过另外一个mySample2指针指向这个对象,如下图示:
之后(C),reset操作第一个指针对象(p=NULL),但是CSample对象没有被释放,因为它mySample2在引用。
只有当最后的引用释放掉后,出了当前作用域时,CSample对象的内存被释放掉。
下面是shared_ptr一些应用案例:
use in containers
using the pointer-to-implementation idiom (PIMPL)
Resource-Acquisition-Is-Initialization (RAII) idiom
Separating Interface from Implementation
1>在容器中使用;
2>PIMPL(pointer to implementation)惯例,即“实现的指针较短”;
3>RAII()惯例; (详细讲解见《学习笔记(4)》)
4>类的使用接口和实现分离
小知识: PIMPL idiom与RAII idiom
1.RAII
RAII是Bjarne Stroustrup教授用于解决资源分配而发明的技术,资源获取即初始化。RAII是C++的构造机制的直接使用,即利用构造函数分配资源,利用析构函数来回收资源.
2.PIMPL
PIMPL是一种应用十分广泛的技术,它的别名也很多,如Opaque pointer, handle classes等。PIMPL是RAII的延展,籍由RAII对资源的控制,把具体的数据布局和实现从调用者视线内移开,从而简化了API接口,也使得ABI兼容变得有可能,Qt和KDE正是使用Pimpl来维护ABI的一致性,另外也为惰性初始化提供途径,以及隐式共享提供了基础。
详细介绍参考:http://c2.com/cgi/wiki PimplIdiom或者wiki;
PIMPL或者RAII是C++程序中众所周知的重要概念, 智能指针只是实现这两种惯用手法的一种方式.
(If you never heard of PIMPL (a.k.a. handle/body) or RAII, grab a good C++ book - they are important concepts every C++ programmer should know. Smart pointers are just one way to implement them conveniently in certain cases)
(3)share_ptr的特点
这里引用《Smart Pointers to boost your code》一文中对share_ptr特点的描述,
shared_ptr
When declaring or using a shared_ptr
shared_ptr
There are virtually no requirements towards T (such as deriving from a base class).
shared_ptr
So you can store objects that need a different cleanup than delete p. For more information, see the boost documentation.
Implicit conversion:
If a type U * can be implicitly converted to T * (e.g., becauseT is base class ofU), a shared_ptr can also be converted toshared_ptr
shared_ptr is thread safe
(This is a design choice rather than an advantage, however, it is a necessity in multithreaded programs, and the overhead is low.)
Works on many platforms, proven and peer-reviewed, the us