Search code examples
c++constructordereference

Am I actually calling ctor and initializing the vtable on an pointer to an object? C++


I feel a little dumb for asking this but I have a situation where I cannot use the new keyword. I need to make sure the constructor is being called for the object pointed to by the variable Utf8Buffer, an example lies below.

Utf8String * pUtf8Buffer;
    void Initialize(void * stringbuffer, size_t bufferlen)
    {
        pUtf8Buffer = (Utf8String*)this->pMemMan->AllocMem(sizeof(Utf8String));
        //In the line below am I calling ctor of the object pointed to by the Utf8Buffer
        //I specifically need ctor to be called on this object to initialize the vtable
        (*pUtf8Buffer) = Utf8String(stringbuffer, bufferlen);
    }

Solution

  • You instead need placement new:

    pUtf8Buffer = (Utf8String*)this->pMemMan->AllocMem(sizeof(Utf8String));
    
    new (pUtf8Buffer) Utf8String(stringbuffer, bufferlen);
    

    And of course if the constructor throws, you need to release the memory. So add a try/catch block, which with a little more type safety looks like this:

    void* pRawBuffer = this->pMemMan->AllocMem(sizeof(Utf8String));
    
    try {
        pUtf8Buffer = new (pRawBuffer) Utf8String(stringbuffer, bufferlen);
    } catch (...) {
        pUtf8Buffer = nullptr;
        this->pMemMan->ReleaseMem(pRawBuffer);
        throw;
    }