定义一般基类
class stCountObject
{
private:
int m_iCount;
public:
stCountObject():m_iCount(0) {}
virtual ~stCountObject() {}
void AddRef(){ ++m_iCount;}//add reference
void RemoveRef()//minu reference
{
--m_iCount;
if(m_iCount <= 0)
{
delete this;
}
}
int GetCount() //Get a reference
{
return m_iCount;
}
};
定义智能指针
template<class T>
class stCountedPtr
{
private:
T *m_pCountObj;
public:
stCountedPtr():m_pCountObj(0){}
stCountedPtr(T* pObject)
{
m_pCountObj = pObject;
if(m_pCountObj)
{
m_pCountObj->AddRef();
}
}
stCountedPtr(const stCountedPtr <T> &pPtr)
{
m_pCountObj = pPtr;
if(m_pCountObj)
{
m_pCountObj->AddRef();
}
}
~stCountedPtr()
{
if(m_pCountObj != 0)
{
int iCount = m_pCountObj->GetCount();
m_pCountObj->RemoveRef();
if(iCount ==1)
{
m_pCountObj = 0;
}
}
}
stCountedPtr<T> &operator = (const stCountedPtr<T> &pPtr)
{
if(m_pCountObj != pPtr.m_pCountObj)
{
if(m_pCountObj != 0)
{
int iCount = m_pCountObj->GetCount();
m_pCountObj->RemoveRef();
if(iCount == 1)
{
m_pCountObj = 0;
}
}
m_pCountObj = pPtr.m_pCountObj;
if(m_pCountObj != 0)
{
m_pCountObj->AddRef();
}
}
return this;
}
/*
T& Operator *()const
{
return *m_pCountObj;
}
T *Oprator->()const
{
return m_pCountObj();
}
Operat T*()const
{
return m_pCountObj;
}
*/
};
class stCLine :public stCountObject
{
public:
stCLine(){}
~stCLine(){}
void DrawLine()
{
printf("DrawLine");
}
};
调用实例
typedef stCountedPtr<stCLine*> stLinePtr;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
stLinePtr line;
line->Draw();
//line->Draw();
return a.exec();
}
内存泄露是很平常的问题,困扰着无数的程序员,如何有效的防止内存泄露智能指针无疑是一个很好的方法。智能指针一个用到模版(template ),另一个是设计模式中的代理模式,对对象的有效管理。