在C++中如何使用GC_malloc然后调用构造函数?

use*_*335 4 c++

我在 C++ 中使用 Boehm 垃圾收集。使用GC_malloc分配后如何调用构造函数?

SomeClass *i = new SomeClass(); // Here the constructor is called.
SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass)); // How to call the constructor here?
Run Code Online (Sandbox Code Playgroud)

jxh*_*jxh 6

您想要执行新的放置。

SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass));
new (j) SomeClass();
Run Code Online (Sandbox Code Playgroud)

这假设分配器已返回适当对齐的内存。

在 C++ 中使用垃圾收集器可能容易出错,因为内存清理步骤不太可能调用内存使用所属对象的析构函数。更安全的是使用智能指针,例如std::unique_ptrstd::shared_ptr