auto_ptr简易实现
最近在看《STL源码剖析》,其中迭代器这一章开头提到,iterator可以看做是一种smart_ptr,同时候捷老师给出了部分auto_ptr的实现,我在这里给出完整实现。
namespace smt_ptr{
template <class T>
class auto_ptr {
public:
explicit auto_ptr(T *p = 0) : pointee(p) {}
template<class U>
auto_ptr(auto_ptr<U>& rhs) : pointee(rhs.release()) {} //拷贝构造函数
~auto_ptr() { delete pointee; }
template<class U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs) {
if (this != &rhs) reset(rhs.release());
return *this;
}
T& operator *() const { return *pointee; }
T* operator ->() const { return pointee; }
T* get() const { return pointee; }
T* release() {
T* tmp = pointee;
pointee = 0;
return tmp;
}
void reset(T *p = 0) {
if( p != pointee) {
delete pointee;
pointee = p;
}
}
private:
T *pointee;
};
}
int main() {
smt_ptr::auto_ptr<std::string> t(new std::string("smart pointer!"));
std::cout<<*t<<std::endl;
smt_ptr::auto_ptr<std::string> tt(t);
std::cout<<*tt<<std::endl;
smt_ptr::auto_ptr<std::string> ttt = tt;
std::cout<<*ttt<<std::endl;
std::cout<<ttt->size()<<std::endl;
}