What Is a Memory Pool?
[1] (Memory Pool) is a memory allocation method. Usually we are used to directly using new, malloc and other APIs to apply for memory allocation. The disadvantage of this is that because the size of the applied memory block is uncertain, it will cause a lot of memory fragmentation and reduce performance when used frequently.
Memory pool
- [1]
- The memory pool is to apply for allocation of a certain number of equal-sized (normally) memory blocks for reserve before actually using the memory. When there is a new memory requirement, a part of the memory block is allocated from the memory pool, and if the memory block is not enough, continue to apply for new memory. A significant advantage of this is that it improves the efficiency of memory allocation.
- in
- There are many implementations of memory pools, and their performance and applicability are also different. Here is a simpler C ++ implementation-the GenericMP template class. (This example is taken from the book "Online game server programming")
- In this example, templates are used to meet the memory requirements of different objects, and the memory blocks in the memory pool are organized in a linked list-based structure.
- GenericMP template class definition
template <class T, int BLOCK_NUM = 50> class GenericMP { public: static VOID * operator new (size_t allocLen) { assert (sizeof (T) == allocLen); if (! m_NewPointer) MyAlloc (); UCHAR * rp = m_NewPointer; m_NewPointer = * reinterpret_cast <UCHAR **> (rp); // Because the first 4 bytes are "forced" to be interpreted as a pointer to the next memory block, here m_NewPointer points to the next memory block for the next allocation use. return rp; } static VOID operator delete (VOID * dp) { * reinterpret_cast <UCHAR **> (dp) = m_NewPointer; m_NewPointer = static_cast <UCHAR *> (dp); } private: static VOID MyAlloc () { m_NewPointer = new UCHAR [sizeof (T) * BLOCK_NUM]; UCHAR ** cur = reinterpret_cast <UCHAR **> (m_NewPointer); // Force to double pointer, this will change the meaning of the first 4 bytes of each memory block. UCHAR * next = m_NewPointer; for (INT i = 0; i <BLOCK_NUM-1; i ++) { next + = sizeof (T); * cur = next; cur = reinterpret_cast <UCHAR **> (next); // In this way, the first 4 bytes of each allocated memory block are "forced" to be interpreted as a pointer to the next memory block, forming the memory block. Linked list structure. } * cur = 0; } static UCHAR * m_NewPointer; protected: ~ GenericMP () { } }; template <class T, int BLOCK_NUM> UCHAR * GenericMP <T, BLOCK_NUM> :: m_NewPointer; GenericMP template class application class ExpMP: public GenericMP <ExpMP> { BYTE a [1024]; }; int _tmain (int argc, _TCHAR * argv []) { ExpMP * aMP = new ExpMP (); delete aMP; }