1. 智能指针(如标准库的auto_ptr,shared_ptr,weak_ptr,boost的scoped_ptr等)主要用于动态内存的管理,同时提供给用户与内置指针一样的使用方法,本条款主要涉及智能指针在构造与析构,复制和赋值,解引等方面的注意点,而非智能指针的实现细节.
2. 智能指针的构造,赋值,析构
智能指针的copy constructor,assignment operator,destructor对应于不同的观念而有不同的实现,主要有三种选择:
1).不允许对象的共享,在调用copy constructor和assignment时转移对象所有权,这样在调用destructor时就可以直接delete智能指针内含的内置指针,如标准库的auto_ptr,其实现可能像这样:
template<class T> class auto_ptr { public: ... auto_ptr(auto_ptr<T>& rhs); auto_ptr<T>& operator=(auto_ptr<T>& rhs); ... }; template<class T> auto_ptr<T>::auto_ptr(auto_ptr<T>& rhs) { pointee = rhs.pointee; rhs.pointee = 0; // 转移对象所有权 } template<class T> auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs) { if (this == &rhs) // 自我赋值的情况 return *this; delete pointee; pointee = rhs.pointee; // 转移对象所有权 rhs.pointee = 0; return *this; }