标签:effective c++ 以对象管理资源 auto_ptr 智能指针
auto_ptr是当前C++标准库中提供的一种智能指针,诚然,auto_ptr有这样那样的不如人意,以至于程序员必须像使用”裸“指针那样非常小心的使用它才能保证不出错,以至于它甚至无法适用于同是标准库中的那么多的容器和一些算法,但即使如此,我们仍然不能否认这个小小的auto_ptr所蕴含的价值与理念。
这里用了Nicolai
M. Josuttis(<<The C++ standard library>>作者)写的一个auto_ptr的版本,并做了少许格式上的修改以易于分析阅读。
namespace std
{
template<class T>
class auto_ptr
{
private:
T* ap;
public:
// constructor & destructor ----------------------------------- (1)
explicit auto_ptr (T* ptr = 0) throw() : ap(ptr){}
~auto_ptr() throw()
{
delete ap;
}
// Copy & assignment --------------------------------------------(2)
auto_ptr (auto_ptr& rhs) throw() :ap(rhs.release()) {}
template<class Y>
auto_ptr (auto_ptr<Y>& rhs) throw() : ap(rhs.release()) { }
auto_ptr& operator= (auto_ptr& rhs) throw()
{
reset(rhs.release());
return *this;
}
template<class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()
{
reset(rhs.release());
return *this;
}
// Dereference----------------------------------------------------(3)
T& operator*() const throw()
{
return *ap;
}
T* operator->() const throw()
{
return ap;
}
// Helper functions------------------------------------------------(4)
// value access
T* get() const throw()
{
return ap;
}
// release ownership
T* release() throw()
{
T* tmp(ap);
ap = 0;
return tmp;
}
// reset value
void reset (T* ptr=0) throw()
{
if (ap != ptr)
{
delete ap;
ap = ptr;
}
}
// Special conversions-----------------------------------------------(5)
template<class Y>
struct auto_ptr_ref
{
Y* yp;
auto_ptr_ref (Y* rhs) : yp(rhs) {}
};
auto_ptr(auto_ptr_ref<T> rhs) throw() : ap(rhs.yp) { }
auto_ptr& operator= (auto_ptr_ref<T> rhs) throw()
{
reset(rhs.yp);
return *this;
}
template<class Y>
operator auto_ptr_ref<Y>() throw()
{
return auto_ptr_ref<Y>(release());
}
template<class Y>
operator auto_ptr<Y>() throw()
{
return auto_ptr<Y>(release());
}
};
}
1
构造函数与析构函数effective c++条款13-17 “以对象管理资源”之auto_ptr源码分析
标签:effective c++ 以对象管理资源 auto_ptr 智能指针
原文地址:http://blog.csdn.net/hustyangju/article/details/41647971