gpt4 book ai didi

c++ - 全局范围内的对象在程序退出时导致崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:50 24 4
gpt4 key购买 nike

看起来当 t 被放在全局范围内时,它会尝试删除它存储的指针?

错误

kk(70137,0x1000d65c0) malloc: *** error for object 0x100b20940: pointer being freed was not allocated
kk(70137,0x1000d65c0) malloc: *** set a breakpoint in malloc_error_break to debug
#include <set>
struct A {
int k = 0;
};
class Test {
public:
static std::set<A*> collection;

~Test(){
collection.clear();
}
};

Test t;
int main() {
A* p = new A();
t.collection.insert(p);
delete p;
}
auto Test::collection = std::set<A*>();

最佳答案

由于 static initialisation order fiasco go 可以在componentAllocatorcollection 之前构造,然后它们将以相反的顺序被销毁。 GameObject 的析构函数然后尝试销毁调用 componentAllocatorTransform,它已经被销毁。

在这种情况下,最简单的解决方法是将 go 对象移动到 main() 中,然后它总是会在静态变量之前被销毁。全局变量很少是必需的,而且经常会导致这样的问题。

关于c++ - 全局范围内的对象在程序退出时导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052368/

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