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.
CodePudding user response:
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/*);
CodePudding user response:
The C 20 solution is std::construct_at
. But you can use the traditional placement new
too.