有时候,我们需要扩展C++来支持一些特性。
听说过智能指针,但是一直不清楚具体的实现和用途。今天书上看到一点。Smart Pointer其实是一个类,模仿built-in pointer的行为,同时提供built-in pointer类型所不支持的一些功能,比如:自动销毁动态创建的对象(类似java的垃圾回收)。
先看一个简单的例子。(《C++ Common Knowledge》)
template <typename T>
class CheckedPtr{
public:
explicit CheckedPtr( T *p ) : p_( p ) {}
~CheckedPtr() { delete p_; }
T *operator ->() { return get(); }
T &operator *() { return *get(); }
private:
T *p_;
T *get() {
if( !p_ )
throw NullCheckedPointer();
return p_;
}
CheckedPtr( const CheckedPtr & );
CheckedPtr &operator =( const CheckedPtr & );
};
看看auto_ptr实现的代码。(《C++标准库》)
namespace std...{
template<class T>
class auto_ptr
...{
private:
T* ap;
public:
// constructor & destructor
explicit auto_ptr (T* ptr = 0) throw() : ap(ptr)...{}
~auto_ptr() throw()
...{
delete ap;
}
// Copy & assignment
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
T& operator*() const throw()
...{
return *ap;
}
T* operator->() const throw()
...{
return ap;
}
// Helper functions
// 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
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());
}
};
}
参考书籍:《C++ Common Knowledge》,《C++标准库》