下面的示例代码将静态成员变量 m_hHeap 存储专用的堆句柄。 堆句柄被初始化为 Classdemo.cpp 文件中的空。 类对象实例化新使用,该重载新称为。 如果句柄为空,将创建堆。 如果句柄不为空,HeapAlloc 称为分配请求的大小。
/* Compile options needed: none
*/
/* Classdemo.h file */
#ifndef __CLASSDEMO_H__
#define __CLASSDEMO_H__
#include <windows.h>
class ClassDemo
{
// private member vars and functions for ClassDemo class
static HANDLE m_hHeap; // fixed heap handle
int m_nMyData[100]; // class data
public:
// public member functions for ClassDemo class
// declaration of new & delete operator overloads
void* operator new(unsigned int nSize);
void operator delete(void* pObj);
static void HeapCreate();
};
#define INITIAL_HEAP_SIZE 4096 // initial heap size
#define CLASS_DEMO_OBJS_MAX 100000 // max number of objects used
inline void* ClassDemo::operator new(unsigned int nSize)
{ // allocate memory using fixed heap
if (m_hHeap == NULL) // if NULL, needs to be created
{
HeapCreate(); // create heap
if (m_hHeap == NULL)
{
return NULL; // HeapCreate failed
}
}
// return pointer to allocated memory
return HeapAlloc(m_hHeap, 0, nSize);
}
inline void ClassDemo::operator delete(void* pObj)
{ // free memory from fixed heap
HeapFree(m_hHeap, 0, pObj);
}
#endif // __CLASSDEMO_H__
/* End of Classdemo.h file */
/* Classdemo.cpp file */
#include <stdio.h>
#include "ClassDemo.h"
HANDLE ClassDemo::m_hHeap = NULL; // Initialize handle
void ClassDemo::HeapCreate()
{
int nRet = IDRETRY; // message box return
int nSize = CLASS_DEMO_OBJS_MAX * sizeof(ClassDemo);// max heap size
m_hHeap = ::HeapCreate(0, // heap flags
INITIAL_HEAP_SIZE, // initial size of heap
nSize); // max heap size
while ((m_hHeap == NULL) && (nRet != IDIGNORE))
{ // keep trying until no error or user ignores
char szMsg[80]; // message buffer
// format message
sprintf(szMsg, "Could allocate a heap of size %d", nSize);
// Display error
nRet = MessageBox(NULL, szMsg, NULL,
MB_ABORTRETRYIGNORE | MB_TASKMODAL);
if (nSize < sizeof(ClassDemo))
{
return; // heap would be too small to be usefull, return
}
switch (nRet)
{
case IDABORT: // user selected abort
{
abort();
}
case IDIGNORE: // user selected ignore
{
return;
}
default: // user selected retry, the message box could not
{ // be displayed, or unknown return code
nSize /= 2; // try a smaller request
m_hHeap = ::HeapCreate(
0, // heap flags
INITIAL_HEAP_SIZE, // initial size of heap
nSize); // max heap size
break;
}
}
}
}
/* End of Classdemo.cpp file */