C++标准程序库提供的auto_ptr是一种智能型指针,帮助程序员防止”被异常抛出时发生资源泄漏“。
1、auto_ptr的初始化
template <class _Tp> class auto_ptr {
private:
_Tp* _M_ptr;
public:
typedef _Tp element_type;
explicit auto_ptr(_Tp* __p = 0) __STL_NOTHROW : _M_ptr(__p) {}
auto_ptr(auto_ptr& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class _Tp1> auto_ptr(auto_ptr<_Tp1>& __a) __STL_NOTHROW
: _M_ptr(__a.release()) {}
#endif /* __STL_MEMBER_TEMPLATES */
上面是STL源代码中class auto_ptr定义的一部分,由上面可以看出一般指针的初始化式不适应于auto_ptr。
auto_ptr可能的初始化式如下:
std::auto_ptr<ClassA> ptr1(new ClassA);//OK
std::auto_ptr<ClassA> ptr2(ptr1);//OK
std::auto_ptr<ClassA> ptr3 = new ClassA;//ERROR
2、auto_ptr的所有权问题
C++标准程序库中规定了一个对象只能被一个auto_ptr对象拥有。
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2(ptr1);//ptr1不再拥有new出来的ClassA对象,所有权转移给ptr2
这点在将auto_ptr作为参数转递给函数时尤为重要,因为这样会导致原来的auto_ptr不再所有之前的对象,后期如果有针对该对象的类的操作,就会发生错误。
void fun(std::auto_ptr<ClassA> p)
{
//do-something
}
int main()
{
std::auto_ptr<ClassA> ptr(new ClassA);
fun(ptr);//当fun运行时,ptr已经不再拥有new出来的ClassA
//do-something on ptr
//这时如果再在ptr上操作就会发生错误
}
3、使用const 限定符来禁止所有权的转移
将auto_ptr加上const限定符后对象的所有权就不能再转移了。另外需要指出的是这里的关键词只是说明不能更改auto_ptr的拥有权,但是可是更改其所拥有的对象。
void fun(const std::auto_ptr<ClassA> p)
{
//do-something
}
int main()
{
const std::auto_ptr<ClassA> ptr(new ClassA);
fun(ptr);//当fun运行时,ptr仍然拥有new出来的ClassA
//do-something on ptr
//这时继续操作ptr就不会出错
ClassA m;
*ptr = m;//可以改ptr所拥有的对象
}