C++之CNoTrackObject类和new delete操作符的重载实例
本文实例讲述了C++中CNoTrackObject类和new delete操作符的重载,分享给大家供大家参考。具体如下:
头信息:
class CNoTrackObject{
public: //在此出过错,没有加public 默认为类的私有变量,MyThreadData继承这个类后也无法访问成员变量
void* operator new(size_t nSize);
void operator delete(void*);
virtual ~CNoTrackObject(){}
};
实现方法如下:
void* CNoTrackObject::operator new(size_t nSize)
{
//申请一块内存
void* p = ::GlobalAlloc(GPTR , nSize);
return p;
}
void CNoTrackObject::operator delete(void* p)
{
if (p != NULL)
{
::GlobalFree(p);
}
}
使用过程如下:
struct MyThreadData:public CNoTrackObject
{
MyThreadData* pNext;
int nShortData;
};
for (int i=0;i<10;i++)
{
<span style="color:#ff0000;">pData = new MyThreadData;</span>
pData->nShortData = i;
list.AddHead(pData);
}
//遍历链表,释放MyThreadData对象占用的空间
pData = (MyThreadData*)list.GetHead();
while(pData != NULL)
{
MyThreadData* pNextData = pData->pNext;
printf("The value is %d\n",pData->nShortData);
<span style="color:#ff0000;">delete pData;</span>
pData = pNextData;
}
希望本文所述对大家的C++程序设计有所帮助