Creating a custom memory pool / memory allocator?

Is it possible in C ++ to create a custom dispenser that works just like this:

{
    // Limit memory to 1024 KB
    ScopedMemoryPool memoryPool(1024 * 1024); 

    // From here on all heap allocations ('new', 'malloc', ...) take memory from the pool.
    // If the pool is depleted these calls result in an exception being thrown.

    // Examples:
    std::vector<int> integers(10);
    int a * = new int [10];
}

I could not find something like this in boost libraries or anywhere else.

Is there a fundamental problem that makes this impossible?

+3
source share
5 answers

You will need to create a custom dispenser that you pass as a template parameter to the vector. This custom allocator will essentially wrap access to your pool and perform any size checks it wants.

+3
source

, ​​, , , .

STL, , , . ( , , .)

. Doug Lea malloc, " ", -.

+2

. " C++". , , . -

++, STL.

malloc, malloc (, dmalloc)

+1

, ?

. . , , , , . . . , .

0

, -, .

Thus, when using staticor a global variable for its implementation, problems with multithreaded functions will arise. Otherwise, this is not a bad way to circumvent statelessness of distributors.

(Of course, you need to pass the second argument to the template, for example vector< int, UseScopedPool >.)

0
source

Source: https://habr.com/ru/post/1763860/


All Articles