Figure 4: Encapsulating the allocation map in an object

class CMemTrack: public CObject
{
   CAddrMap    m_AddrMap;              // Internal map

public:

   // Allocation and deallocation tracking methods.
   LPVOID      
   Allocate(size_t nSize, char* lpszFileName, int nLine);

   void        Deallocate(void* pData);

   // Dump methods.
   void        DumpMemoryLeaks();      // Automatically called.
   static void Dump();                 // Can be manually called.

   // Cleanup method.
   void        Cleanup();
};

// The global memory track object.
extern CMemTrack  afxMemTrack;

// The new operator simply invokes CMemTrack::Allocate().
inline void* 
operator new(size_t nSize, char* pszFileName, int nLine)
{
   return afxMemTrack.Allocate(nSize, pszFileName, nLine);
}

// The delete operator simply invokes CMemTrack::Deallocate().
inline void operator delete(void * pData)
{
   afxMemTrack.Deallocate(pData);
}