gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:46:19 25 4
gpt4 key购买 nike

我觉得问这个问题有点傻,但我遇到了无法使用 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 block ,它具有更多的类型安全性,如下所示:

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

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

关于c++ - 我实际上是在调用 ctor 并在指向对象的指针上初始化 vtable 吗? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com