Search code examples
c++memory-managementconstructormemory-pool

Initializing class/struct from a void pointer


I have a memory pool that is allocated as char*. When I want to create an object I request memory from that pool that returns a char* somewhere in that pool cast to a void*.

So when I create a object I do this

Data* poolTest = (Data*)pool->GetMemory(sizeof(Data));

But this does not allow me to access the constructor of the class Data and I have to assign the value after I create it.

Is there anyway to change this to allow me to pass arguments the same way I would do with

Data* test = new Data(5, 5, 5);

Not sure if it possible.


Solution

  • It seems placement new is what you are looking for. Basically you give it raw memory, and create objects with dynamic storage duration in the provided memory region. Managing the lifetimes of the memory region and created objects is up to you, of course.

    Example from the docs:

    char* ptr = new char[sizeof(T)]; // allocate memory
    T* tptr = new(ptr) T;            // construct in allocated storage ("place")
    tptr->~T();                      // destruct
    delete[] ptr;                    // deallocate memory
    

    For reference:

    Possibly std::uninitialized_fill() can also fit your use case:

    If you have access to C++17 features, also have a look at std::uninitialized_default_construct() and std::uninitialized_value_construct():

    Maybe you should consider writing an allocator to wrap your memory pool: