智能指针(smart pointer)是存储指向动态分配(堆)对象指针的类,能够在适当的时间自动删除指向的对象外,能够确保正确的销毁动态分配的对象。
标准库的智能指针为auto_ptr。boost库的智能指针族在功能上做了扩展。
1.auto_ptr
auto_ptr注意事项如下。
①auto_ptr不能共享所有权。
②auto_ptr不能指向数组。
③auto_ptr不能作为容器成员。
boost库对智能指针族做了扩展,使用方便。
①scoped_ptr-<boost/scoped_ptr.hpp>:简单单一对象唯一所有权,不可复制。
②scoped_array<boost/scoped_array.hpp>:简单数组唯一所有权,不可复制。
③shared_ptr<boost/shared_ptr.hpp>:在多个指针共享的对象所有权。
④shared_array<boost/shared_array.hpp>:在多个指针共享的数组所有权。
⑤weak_ptr<boost/weak_ptr.hpp>:属于shared_ptr对象无所有权的观察者。
标准库的智能指针为auto_ptr。boost库的智能指针族在功能上做了扩展。
1.auto_ptr
auto_ptr注意事项如下。
①auto_ptr不能共享所有权。
②auto_ptr不能指向数组。
③auto_ptr不能作为容器成员。
④不能通过赋值操纵来初始化auto_ptr。
boost库对智能指针族做了扩展,使用方便。
①scoped_ptr-<boost/scoped_ptr.hpp>:简单单一对象唯一所有权,不可复制。
②scoped_array<boost/scoped_array.hpp>:简单数组唯一所有权,不可复制。
③shared_ptr<boost/shared_ptr.hpp>:在多个指针共享的对象所有权。
④shared_array<boost/shared_array.hpp>:在多个指针共享的数组所有权。
⑤weak_ptr<boost/weak_ptr.hpp>:属于shared_ptr对象无所有权的观察者。
⑥intrusive_ptr<boost/intrusive_ptr.hpp>:带有侵入式引用计数的对象共享所有权。
模拟共享对象所有权指针的实现方式,模拟shared_ptr。示例代码如下。
template <typename T>
class SmartPtr
{
public:
SmartPtr(T* p=0):ptr(p),pUse(new size_t()) {}
SmartPtr(const SmartPtr& src):ptr(src.ptr),pUse(src.pUse) {++*pUse;}
SmartPtr& operator=(const SmartPtr& rhs)
{
++*rhs.pUse;
decrUse();
ptr = rhs.ptr;
pUse = rhs.pUse;
return *this;
}
T* operator->() { if(ptr) return ptr; else return null; }
T& operator*() { if(ptr) return *ptr; else return null; }
~SmartPtr() { decrUse(); }
size_t usecount() { return *pUse; }
private:
void decrUse()
{
if(--*pUse == 0)
{
delete ptr;
ptr = null;
delete pUse;
pUse = null;
}
}
T* ptr;
size_t* pUse;
};