gpt4 book ai didi

c++ - 使用 Boehm GC 时 C++ 内存泄漏的原因

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:58 26 4
gpt4 key购买 nike

这段代码导致了我的内存泄漏,我不确定为什么。

[编辑] 包含来自 here 的代码质疑:

#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() 的内容时,我没有内存泄漏,这让我相信问题出在 map 没有清理上,但是我使用的是 gc 分配器,所以我不确定下一步要看哪里。想法?

最佳答案

'gc 分配器' 正在分配和管理这种类型的对象:

std::pair<const std::string, AlObj*>

仅仅因为这个对象中有一个指针并不意味着分配器将对其调用 delete。

如果你想让在setUp()中创建的对象成为GC那么你需要通过GC来分配它们。或者学习使用 boost:ptr_map 或 shared_ptr。

map 销毁(而不是删除)它拥有的对象。在这种情况下,它拥有指针而不是指针指向的内容。因此,本地图被销毁时,它会释放与 map 相关的所有内容以及它拥有的对象(对于指针,这意味着它什么都不做)。

如果您有一个包含指针的 map (或其他容器)。您必须手动删除指针,否则会发生内存泄漏。或者,您可以使用 boost::ptr_map 或包含 share_ptr 的 map

关于c++ - 使用 Boehm GC 时 C++ 内存泄漏的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/292893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com