您的位置:首页 > 其它

智能指针的类实现

2010-04-11 15:21 274 查看
//以下是智能指针的声明
template<typename T>
class CounterPtr
{
private:
class Impl
{
public:
Impl(T* pp) : p(pp),refs(1){}
~Impl() {delete p;}
private:
T* p;
size_t refs;
};
Impl* impl_;
public:
explicit CounterPtr(T* p)
: impl_(new Impl(p)){}
~CounterPtr(){Decrement();}
CounterPtr(const CounterPtr& other)
:impl_(other.impl_)
{
Increment();
}
CounterPtr& operator=(const CounterPtr& other)
{
if(impl_ != other.impl_)
{
Decrement();
impl_ = other.impl_;
Increment();
}
return *this;
}
T* operator->() const
{
return impl_->p;
}
T& operator*() const
{
return *(impl_->p);
}
private:
void Decrement()
{
if( -- (impl_->refs) == 0)
{
delete impl_;
}
}
void Increment()
{
++(impl_->refs);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: