如何使用GC_malloc,然后在c++中调用构造函数

How to use GC_malloc and then call the constructor in C++?

本文关键字:c++ 调用 构造函数 然后 何使用 GC malloc      更新时间:2023-10-16

我在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?

你想执行一个新的位置。

SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass));
new (j) SomeClass();

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

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

SomeClass过载operator new:

void* operator new(size_t size)
{
    return GC_malloc(size);
}

现在你可以用operator new调用SomeClass的构造函数的任何重载,并且将调用GC_malloc函数来分配SomeClass的新实例的内存。

您也可以在SomeClass中重载operator delete:

void operator delete(void* ptr)
{
    assert(0);
}

可选地,在assert(0);之前,调用一个跨平台方法,向用户显示一个正确的错误文本消息,说明SomeClass*或任何指向SomeClass实例的指针一般不应该是delete operator的操作数,因为所有由new operator创建的SomeClass实例都是由Boehm垃圾收集器管理的。