集成 Boehm 垃圾收集器和 C 标准库
要将 Boehm 保守垃圾收集器与 C 标准库集合无缝集成,有两种主要方法:
重新定义运算符::new
此方法涉及重新定义运算符::new以使用Boehm的GC。但是,它可能与现有 C 代码冲突,并且可能无法在不同编译器之间移植。
显式分配器参数
您可以使用而不是重新定义运算符 ::new标准库集合的第二个模板参数,用于指定自定义分配器。该参数控制如何分配集合内部数据结构的内存。
使用 std::vector 的示例
以下代码演示了如何将 gc_allocator 与 std:: 一起使用:矢量:
#include
#include
std::vector> myVector(10); // Allocate vector with GC-specific allocator
std::string Integration
对于std::string,您可以使用GC_malloc_atomic显式分配内部字符数组:
#include
#include
std::string myString((char*)GC_malloc_atomic(10), 10); // Allocate string with GC_malloc_atomic
分配字符串注意:
Boehm GC 与 g 集成时,一般不建议重新定义操作符 ::new 。相反,更喜欢使用显式分配器参数方法以获得更大的可移植性和兼容性。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3