作用域指针
当我们并不打算复制智能指针,只是想保证被分配的资源将被正确地回收,可以采用一种简单得多的解决方案:作用域指针。如下示例代码:
template <typename T>
class ScopedPtr
{
public:
explicit ScopedPtr(T* p = NULL)
:ptr_(p)
{
}
ScopedPtr<T>& operator=(T* p)
{
if(ptr_ != p)
{
delete ptr_;
ptr_ = p;
}
return *this;
}
~ScopedPtr()
{
delete ptr_;
}
T* Get() const
{
return ptr_;
}
T* operator->()const
{
SCPP_TEST_ASSERT(ptr_ != NULL,
"Attempt to use operator -> on NULL pointer.");
return ptr_;
}
T& operator*()const
{
SCPP_TEST_ASSERT(ptr_ != NULL,
"Attempt to use operator * on NULL pointer.");
return *ptr_;
}
//把所有对象的所有权释放给调用者
T* Release()
{
T* p = ptr_;
ptr_ = NULL;
return p;
}
private:
T* ptr_;
//复制被禁止
ScopedPtr(const ScopedPtr<T>& rhs);
ScopedPtr<T>& operator=(const ScopedPtr<T>& rhs);
};
原文地址:http://blog.csdn.net/kerry0071/article/details/37812071