C ++ placement new with the memory pool

Reference: https://blog.csdn.net/Kiritow/article/details/51314612

Program (for example, the listener, the server program) Sometimes we need to be able to run for a long time these programs are running 24 * 7, we should not use the new and delete standard library (malloc and free are also considered). This is because the operation of program memory and applications are constantly being released, frequent application and release will lead to memory fragmentation, lack of memory and other problems affecting the normal operation of the program. More often does not allow the memory core application failure, but does not allow the emergence of abnormal, it is necessary to ensure that each application is successful memory (usually kernel, of course, do not want to be interrupted daemon is also true). In such extreme demands, the benefits of memory pool is greatly highlights out.

In C ++, a memory cell can be achieved by placement new. Of course, there are also boost memory pool finished (boost :: pool) to achieve, do not make too much explanation.

The following is a code used placement new

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
 
void* GlobalBuffer=nullptr;
 
void InitGlobalBuffer()
{
    GlobalBuffer=malloc(10240);
    cout<<"GlobalBuffer Initialized. Pointer="<<GlobalBuffer<<",size= 10240"<<endl;
}
void DestroyGlobalBuffer()
{
    free(GlobalBuffer);
}
 
class STK
{
public:
    STK()
    {
        cout<<"In STK::STK(), this="<<this<<endl;
    }
    ~STK()
    {
        cout<<"In STK::~STK(), this="<<this<<endl;
    }
private:
    int a,b,c;
};
 
int main()
{
    cout<<"Main Start"<<endl;
    InitGlobalBuffer();
    STK* pstk=new (GlobalBuffer) STK;
    pstk->~STK();
    DestroyGlobalBuffer();
    return 0;
}

The above code to implement initializing global memory pool by calling InitGlobalBuffer () (of course, also be packaged as a memory pool, etc. ...), then,

STK* pstk=new (GlobalBuffer) STK;

This line object is configured on the memory (the memory cell) has been allocated. The construction process does not throw an exception because of insufficient memory or fail. (However, the constructor throws an exception may still lead to terminate, it should be noted)

After successfully construct an object can normally use the object.

Note that the need to manually call the destructor of the object after use, the following

pstk->~STK();

This step invokes the class destructor STK STK :: ~ STK (), but the memory will not be released.

Finally () to achieve the release of the global memory pool by DestroyGlobalBuffer.

Memory pool technology can significantly reduce the memory application time, completely avoid memory fragmentation, lack of memory and other problems. Associated with the memory pool of technology, there are many, this is not described in detail.

Guess you like

Origin www.cnblogs.com/jmliao/p/11700491.html