我实际上是在调用 ctor 并在指向对象的指针上初始化 vtable 吗? C++

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

我问这个问题有点傻,但我遇到了无法使用 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;
}