如何使用GC_malloc,然后在c++中调用构造函数
How to use GC_malloc and then call the constructor in 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?
你想执行一个新的位置。
SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass));
new (j) SomeClass();
此操作假设分配器已返回适当对齐的内存。
在c++中使用垃圾收集器可能容易出错,因为内存清理步骤不太可能调用内存使用所属对象的析构函数。更安全的是使用智能指针,如std::unique_ptr
或std::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垃圾收集器管理的。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用