我实际上是在调用 ctor 并在指向对象的指针上初始化 vtable 吗?C++
Am I actually calling ctor and initializing the vtable on an pointer to an object? C++
我觉得问这个有点愚蠢,但我有一个不能使用新关键字的情况。我需要确保为变量 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;
}
相关文章:
- 分段错误 - 读取初始化指针的数组
- 初始化指针的常量向量
- 初始化指针或引用成员变量以指向另一个成员
- C++初始化指针/引用/复制细微差别
- 使用无效指针初始化指针声明符的行为是否未定义?
- 在一行中初始化指针(新uint8_t[高度*宽度*3])
- 如何使用可变模板初始化指针?
- 初始化指针时出现写入访问冲突
- C 错误,带有卷曲括号的字面初始化指针
- 重新初始化指针是一种不好的做法吗?
- 初始化指针?C
- 初始化指针向量的向量
- 如何在类函数中正确初始化指针
- C++初始化指针会使应用程序随机崩溃
- 初始化指针结构 - 内存中的外观
- 如何使用struct构造函数在结构中初始化指针阵列
- 在一行中声明并初始化指针到类实例
- 分配数组与初始化指针
- QT 中的非初始化指针
- 使用地址值初始化指针