智能指针是一种资源管理类,通过对原始指针进行封装,在资源管理对象进行析构时对指针指向的内存进行释放;通常使用引用计数方式进行管理,一个基本实现如下:
class Object;
class SmartPointer;
class Counter
{
friend class SmartPointer;
public:
Counter()
{
ptr = NULL;
cnt = 0;
}
Counter(Object* p)
{
ptr = p;
cnt = 1;
}
~Counter()
{
delete ptr;
}
private:
Object* ptr;
int cnt;
};
class SmartPointer
{
public:
SmartPointer(Object* p)
{
ptr_counter = new Counter(p);
}
SmartPointer(const SmartPointer &sp)
{
ptr_counter = sp.ptr_counter;
++ptr_count->cnt;
}
SmartPointer& operator=(const SmartPointer &sp)
{
++sp.ptr_counter->cnt;
--ptr_counter->cnt;
if (ptr_counter->cnt == 0)
{
delete ptr_counter;
}
ptr_counter = sp.ptr_counter;
}
~SmartPointer()
{
--ptr_counter->cnt;
if (ptr_counter->cnt == 0)
{
delete ptr_counter;
}
}
private:
Counter* ptr_counter;
};