问这个问题我有点傻,但是我无法使用new关键字。我需要确保正在为变量Utf8Buffer所指向的对象调用构造函数,下面是一个示例。

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);
    }

最佳答案

相反,您需要placement new

pUtf8Buffer = (Utf8String*)this->pMemMan->AllocMem(sizeof(Utf8String));

new (pUtf8Buffer) Utf8String(stringbuffer, bufferlen);


当然,如果构造函数抛出异常,则需要释放内存。因此,添加一个try / catch块,它具有更多类型安全性,如下所示:

void* pRawBuffer = this->pMemMan->AllocMem(sizeof(Utf8String));

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

10-04 14:32