C++采用引用计数进行内存管理

来源:互联网 发布:燃气灶烤箱一体机 知乎 编辑:程序博客网 时间:2024/06/05 00:59

1.定义引用计数基类CRefCounter

2.定义一个资源类继承自类CRefCounter,则该资源类即具备了引用计数功能

3.定义一个智能指针模板类,来管理资源类

 //引用计数基类CRefCounter

class CRefCounter

{

public:

void Duplicate() { m_nCount++;}

        //当计数为0时析构自己

void Release() { if(--m_nCount == 0) delete this;}

protected:

//构造函数

CRefCounter():m_nCount(0) {}

//拷贝构造函数

CRefCounter(const CRefCounter& rhs):m_nCount(0) {}

//赋值函数

        CRefCounter& operator=(const CRefCounter& rhs) { return *this;}

         //析构函数

         ~CRefCounter() {}

private:

volatile long m_nCount;

}


//资源类

//任何一种类型的数据只要继承CRefCounter

//便具有引用计数功能
class Param : public CRefCounter
{
public:
//构造函数
Param():m_iDate(0x31) {}
~Param() {}

private:
//私有成员和数据
int m_iDate;

};


//智能指针类

template <class T>

class SmartPointer

{

public:

//构造函数

SmartPointer(T* _pT = 0):m_pT(_pT)

{

if(_pT != NULL)

{

//资源引用计数加1

m_pT->Duplicate();

}

}

//析构函数

//智能指针析构自己时,会将管理的资源的计数减1

//如果资源的引用计数值减1后为0,则资源析构自己

        ~SmartPointer()

        {

if(m_pT)

m_pT->Release();

}

//拷贝构造函数
SmartPointer(const SmartPointer<T>& rhs) 
{
//资源引用计数加1
m_pT = rhs.m_pT;
m_pT->Duplicate();
}

         //赋值函数

        SmartPointer<T>& operator=(const SmartPointer<T>& rhs)

{

//证同测试

if(this != &rhs)

{

///注意在赋值前,此处要对m_pT做判空处理
//如果为空则表示该智能指针未管理资源对象
//不为空,当前智能指针管理着资源对象,必须先将当前资源对象计数减1,然后再赋值
if(m_pT != NULL)
{
m_pT->Release();
}


//管理新资源对象
m_pT = rhs.m_pT;
m_pT->Duplicate();

}

return *this;

}

//重载*运算符

T&  operator*()  const

        { return *m_pT;}

//重载->运算符

T* operator->() const

{ return m_pT;} 

private:

T* m_pT;//资源指针

}



       




0 0
原创粉丝点击