一个C++中智能指针的设计
一个C++中智能指针的设计
在C++中,智能指针是存储一些动态分配对象或者资源的类,主要用于控制资源或者动态对象的使用生存期,设计的目的如下:
- 保证能够正确的分配和销毁动态对象或者资源,以防止内存泄露等问题。
- 跟踪对象或者资源的使用情况。
智能指针的实现一般都是使用引用计数,将一个计数器与使用的指针相关联起来,此时引用计数器跟踪该所属类有外部多少共享。因此在实现的时候,就有两个根本的部分
- 计数表示。用于实现对动态对象或者资源使用的计数。
- 指针表示。用于将动态对象或者资源的指针使用间接表现。
根据智能指针主要是上面两大部分,智能指针可以称为“智能计数指针”,智能主要是计数的意思,当然计数的用途就因应用而不同了,或者只是为了跟踪,或者是为了资源管理,或者是为了防止多次释放等等。
一,智能指针实现
下面的模板类,用于实现对指针的封装,其实现的功能如下:
- 指针构造。根据需要被封装的动态对象或者资源的指针,构造智能指针,一般在构造时,会将资源的计数加1;
- 指针运算符重载。下面重载了*,=,->等运算符。
- 指针数据。一个指向模板类型的指针,T* ptr_
- template <class T>
- class scoped_refptr {
- public:
- scoped_refptr() : ptr_(NULL) {
- }
- scoped_refptr(T* p) : ptr_(p) {
- if (ptr_)
- ptr_->AddRef();
- }
- scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
- if (ptr_)
- ptr_->AddRef();
- }
- template <typename U>
- scoped_refptr(const scoped_refptr<U>& r) : ptr_(r.get()) {
- if (ptr_)
- ptr_->AddRef();
- }
- ~scoped_refptr() {
- if (ptr_)
- ptr_->Release();
- }
- T* get() const { return ptr_; }
- operator T*() const { return ptr_; }
- T* operator->() const { return ptr_; }
- T* release() {
- T* retVal = ptr_;
- ptr_ = NULL;
- return retVal;
- }
- scoped_refptr<T>& operator=(T* p) {
- // AddRef first so that self assignment should work
- if (p)
- p->AddRef();
- if (ptr_ )
- ptr_ ->Release();
- ptr_ = p;
- return *this;
- }
- scoped_refptr<T>& operator=(const scoped_refptr<T>& r) {
- return *this = r.ptr_;
- }
- template <typename U>
- scoped_refptr<T>& operator=(const scoped_refptr<U>& r) {
- return *this = r.get();
- }
- void swap(T** pp) {
- T* p = ptr_;
- ptr_ = *pp;
- *pp = p;
- }
- void swap(scoped_refptr<T>& r) {
- swap(&r.ptr_);
- }
- protected:
- T* ptr_;
- };
有了这个类之后,我们可以定义一个指针,如针对class window的智能指针
scoped_refptr<window> win;
此时,上面的模板就会包含一个window *ptr_的指针,从上面可以看出,为了能够正常工作,这类型的指针都必须要实现AddRef和Release方法,这应该不会是要求在class window中实现的吧?那也不太不符合封装的正常逻辑了。答案是:当然不会在class window中实现,这两个方法主要是针对计数的方法,专门针对class window封装一个计数器类,下面的计数器封装。
|
评论暂时关闭