c++代码
template <typename T>
class SmartPtr
{
public:
SmartPtr(T* p = 0):ptr(p),count(new int(1)){}
//复制构造函数
SmartPtr(const SmartPtr& sp):ptr(sp.ptr),count(sp.count)
{
++count;
}
//重载赋值操作符
SmartPtr& operator=(const SmartPtr& rp)
{
++*rp.count;
DecCount();
ptr = rp.ptr;
count = rp.count;
return *this;
}
//重载赋值操作符
SmartPtr& operator=(SmartPtr& rp)
{
++*rp.count;
DecCount();
ptr = rp.ptr;
count = rp.count;
return *this;
}
~SmartPtr()
{
DecCount();
}
private:
void DecCount()
{
if(--*count <= 0)
{
delete ptr;
delete count;
ptr = NULL;
count = NULL;
}
}
private:
T* ptr;
int* count;
};
智能指针一种通用的方法就是采用引用计数的方法,将智能指针与类的对象联系在一起,引用计数共有多少个对象共享同一个指针。
当创建新对象时,初始化指针并设置计数器为1。
当对象作为另外一个对象副本创建时,拷贝构造函数拷贝指针并且增加计数器的值。
当对一个对象赋值时,赋值操作符减少左操作数所指对象的计数器(当计数器被减为0时,删除对象),并增加右操作数所指的引用计数。
调用析构函数时,减少引用计数(当计数器被减为0时,删除对象)

本文介绍了一种基于C++的智能指针实现方法,通过模板定义了一个名为SmartPtr的类,该类利用引用计数来管理堆上分配的对象生命周期。文章详细解释了复制构造函数、赋值操作符重载及析构函数的作用,并阐述了如何通过增加或减少引用计数来避免内存泄漏。
1149

被折叠的 条评论
为什么被折叠?



