Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call constructor on uninitialized memory in C++

I have some legacy C++ (10+ years old) that I am trying to compile where there is a buffer/allocator, that is used to get some memory for a new object. Then a function, std::_Construct, is called that I assume is used to call the constructor for the object (since the allocator only returns a void*). But I suspect that it is only a feature of an older version of Visual Studio (I can’t find anything from before VS2015), so I am wondering: How can I call the constructor on a piece of uninitialized memory that I have casted to the class I’m trying to construct?

Here is a little pseudo-code of what I’m trying to achieve:

BufferManagementClass mBuffMan; // "allocator"

class A { ... };

A* initObject() {
    A* pA = static_cast<A*>(mBuffMan.GetBuffer(sizeof(A))); // GetBuffer returns void*, so I cast it.
    if (pA == NULL)
        return NULL;

    /*
    How do I call the constructor of the memory pA points to here?
    I assume that is needed before I can call any methods in pA?
    */

    pA->someFunc();
    pA->someOtherFunc();
    return pA;
}

I have converted the project to C++14 (since that’s the earliest standard version that VS2019 supports) by the way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is no std::_Construct in standard library. The underscore + upper case prefix implies that this is a language extension or implementation detail of the standard library. Since it has disappeared in version change, it was probably the latter.

The standard way to create an object in uninitalised storage that has been available for 24+ years is to use placement-new syntax:

void* memory = mBuffMan.GetBuffer(sizeof(A))
A* aP = new(memory) A(/*constructor arguments/*);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading