home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / mfc / src / fixalloc.h < prev    next >
C/C++ Source or Header  |  1998-06-16  |  2KB  |  78 lines

  1. // fixalloc.h - declarations for fixed block allocator
  2.  
  3. #ifndef __FIXALLOC_H__
  4. #define __FIXALLOC_H__
  5.  
  6. #include "afxplex_.h"
  7.  
  8. /////////////////////////////////////////////////////////////////////////////
  9. // CFixedAlloc
  10.  
  11. class CFixedAlloc
  12. {
  13. // Constructors
  14. public:
  15.     CFixedAlloc(UINT nAllocSize, UINT nBlockSize = 64);
  16.  
  17. // Attributes
  18.     UINT GetAllocSize() { return m_nAllocSize; }
  19.  
  20. // Operations
  21. public:
  22.     void* Alloc();  // return a chunk of memory of nAllocSize
  23.     void Free(void* p); // free chunk of memory returned from Alloc
  24.     void FreeAll(); // free everything allocated from this allocator
  25.  
  26. // Implementation
  27. public:
  28.     ~CFixedAlloc();
  29.  
  30. protected:
  31.     struct CNode
  32.     {
  33.         CNode* pNext;   // only valid when in free list
  34.     };
  35.  
  36.     UINT m_nAllocSize;  // size of each block from Alloc
  37.     UINT m_nBlockSize;  // number of blocks to get at a time
  38.     CPlex* m_pBlocks;   // linked list of blocks (is nBlocks*nAllocSize)
  39.     CNode* m_pNodeFree; // first free node (NULL if no free nodes)
  40.     CRITICAL_SECTION m_protect;
  41. };
  42.  
  43. #ifndef _DEBUG
  44.  
  45. // DECLARE_FIXED_ALLOC -- used in class definition
  46. #define DECLARE_FIXED_ALLOC(class_name) \
  47. public: \
  48.     void* operator new(size_t size) \
  49.     { \
  50.         ASSERT(size == s_alloc.GetAllocSize()); \
  51.         UNUSED(size); \
  52.         return s_alloc.Alloc(); \
  53.     } \
  54.     void* operator new(size_t, void* p) \
  55.         { return p; } \
  56.     void operator delete(void* p) { s_alloc.Free(p); } \
  57.     void* operator new(size_t size, LPCSTR, int) \
  58.     { \
  59.         ASSERT(size == s_alloc.GetAllocSize()); \
  60.         UNUSED(size); \
  61.         return s_alloc.Alloc(); \
  62.     } \
  63. protected: \
  64.     static CFixedAlloc s_alloc \
  65.  
  66. // IMPLEMENT_FIXED_ALLOC -- used in class implementation file
  67. #define IMPLEMENT_FIXED_ALLOC(class_name, block_size) \
  68. CFixedAlloc class_name::s_alloc(sizeof(class_name), block_size) \
  69.  
  70. #else //!_DEBUG
  71.  
  72. #define DECLARE_FIXED_ALLOC(class_name)     // nothing in debug
  73. #define IMPLEMENT_FIXED_ALLOC(class_name, block_size)   // nothing in debug
  74.  
  75. #endif //!_DEBUG
  76.  
  77. #endif
  78.