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

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

本文关键字:初始化 指针 vtable C++ 调用 实际上 ctor 对象      更新时间:2023-10-16

我觉得问这个有点愚蠢,但我有一个不能使用新关键字的情况。我需要确保为变量 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);
    }
相反,

您需要放置新位置:

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