智能指针的类实现
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);
}
};
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);
}
};
相关文章推荐
- 14.智能(smart)指针,实现细节
- Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析
- 智能指针的实现尝试
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析
- 用c++简单实现智能指针(转)
- 第十三章——复制控制 智能指针的code实现
- C++中智能指针的实现
- 自己实现智能指针
- 一个智能指针的实现(改进)
- C++中智能指针的工作原理和简单实现
- 引用计数的智能指针的实现
- c++实现引用计数智能指针
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- c++ 一种智能指针的实现
- [C++]智能指针的实现与使用
- (转)Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析
- 智能指针 安全引用的实现
- 利用读写锁和智能指针来实现多线程下对资源的多个地方读和多个地方写的实现。
- 模仿的智能指针的一个简单实现