我有一个模拟程序。在模拟的主要类中,我正在“创建+添加”和“删除+销毁”代理。在运行时添加和删除列表
问题是,有一次(每3-4次运行一次程序)程序崩溃,因为我显然在主循环中调用无效代理的函数。该程序在大多数时间工作得很好。列表中通常有数千个代理。
- 我不知道我的循环中有无效代理的可能性如何。
调试代码非常困难,因为我在“Agent :: Step函数”内部收到内存异常(这太迟了,因为我无法理解列表中的无效代理是如何调用的)。
当我查看Agent :: Step函数内的代理引用(异常点)时,代理中的数据没有意义,甚至没有初始化数据。所以这绝对是无效的。
void World::step() { AddDemand(); // run over all the agents and check whether they have remaining actions // Call their step function if they have, otherwise remove them from space and memory list<Agent*>::iterator it = agents_.begin(); while (it != agents_.end()) { if (!(*it)->AllIntentionsFinished()) { (*it)->step(); it++; } else { (*it)->removeYourselfFromSpace(); //removes its reference from the space delete (*it); agents_.erase(it++); } } } void World::AddDemand() { int demand = demandIdentifier_.getDemandLevel(stepCounter_); for (int i = 0; i < demand; i++) { Agent* tmp = new Agent(*this); agents_.push_back(tmp); } } Agent: bool Agent::AllIntentionsFinished() { return this->allIntentionsFinished_; //bool flag will be true if all work is done }
1-难道循环(即在多线程,如果可能的运行)的VStudio 2012优化造成的问题?
2-关于调试代码的任何建议?
谢谢。它是否也适用于列表(因为我使用列表而不是矢量)。 我不使用线程,但我认为vstudio 2012编译器尝试使用线程(如果它认为可以)。 – wmac
呃,是的 - 抱歉,那是错误的链接 - 它实际上是我尝试链接的页面引用的位置,但链接到列表页面会更有意义:) – kfsone
更改顺序并未解决问题。使用“it = agents_erase(it);”也没有解决问题。我想我应该再仔细看看我的所有代码。你的链接也指向同样的问题btw。 – wmac