C++之CNoTrackObject類和new delete操作符的重載實例。本站提示廣大學習愛好者:(C++之CNoTrackObject類和new delete操作符的重載實例)文章只能為提供參考,不一定能成為您想要的結果。以下是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 >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 >delete pData;</span>
pData = pNextData;
}
願望本文所述對年夜家的C++法式設計有所贊助