[英]Cause of a memory leak in C++ when using the Boehm GC
这段代码对我造成了内存泄漏,我不确定为什么。
[编辑] 此处包含的代码有疑问:
#include "src/base.cpp"
typedef std::map<std::string, AlObj*, std::less<std::string>,
gc_allocator<std::pair<const std::string, AlObj*> > > KWARG_TYPE;
AlInt::AlInt(int val) {
this->value = val;
this->setup();
}
// attrs is of type KWARG_TYPE
void AlInt::setup() {
this->attrs["__add__"] = new AddInts();
this->attrs["__sub__"] = new SubtractInts();
this->attrs["__mul__"] = new MultiplyInts();
this->attrs["__div__"] = new DivideInts();
this->attrs["__pow__"] = new PowerInts();
this->attrs["__str__"] = new PrintInt();
}
int main() {
while (true) {
AlObj* a = new AlInt(3);
}
}
AlInt继承自AlObj,而后者又继承自gc。 当我注释掉setup()的内容时,没有内存泄漏,这使我相信问题在于映射未清除,但是我正在使用gc分配器,因此我不确定接下来要看的地方。 思考?
“ gc分配器”正在分配和照顾这种类型的对象:
std::pair<const std::string, AlObj*>
仅仅因为该对象中有一个指针并不意味着它会在分配器上调用delete。
如果要将setUp()中创建的对象作为GC,则需要通过GC分配它们。 或学习使用boost:ptr_map或shared_ptr。
映射会销毁(而不是删除)其拥有的对象。 在这种情况下,它拥有指针, 而不是指针指向的指针。 因此,在销毁地图时,它会取消分配与地图及其所拥有的对象关联的所有内容(对于指针,这意味着它什么也不做)。
如果您有一个包含指针的地图(或其他容器)。 您必须手动删除指针,否则会发生内存泄漏。 或者,您可以使用boost :: ptr_map或包含share_ptr的地图
实质上,我要说的是,AlObj似乎已被破坏,但不是它的成员(因为除非我将内容放入attrs,否则它不会泄漏)。
分配器正在删除您的货币对。 但是删除一对并不会删除恰好是指针的一对成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.