一个smart point的实现(摘自 More Effective C++)
template<class T>
class auto_ptr
{
public:
explicit auto_ptr(T *p = 0): pointee(p) {}
template<class U>
auto_ptr(const auto_ptr<U>& rhs): pointee(rhs.release()) {} //copy constructor
~auto_ptr() { delete pointee; }
template<class U>
auto_ptr<T>& operator=(const auto_ptr<U>& rhs) //copy operator
{
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 *oldPointee = pointee;
pointee = 0;
return oldPointee;
}
void reset(T *p = 0)
{
if (pointee != p) {
delete pointee;
pointee = p;
}
}
private:
T *pointee;
template<class U> friend class auto_ptr<U>;
};
本文介绍了一个C++中auto_ptr智能指针的实现案例,该实现来源于《More Effective C++》一书,详细展示了auto_ptr的构造、析构、赋值操作等关键方法。
371

被折叠的 条评论
为什么被折叠?



