fixalloc.h 2.0 KB

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