我有一个模拟程序。在模拟的主要课程中,我正在“创建+添加”和“删除+销毁”代理。
问题是有时(我每运行程序 3-4 次)程序崩溃,因为我显然在主循环中调用了无效代理的函数。该程序大部分时间都运行良好。列表中通常有数千个代理。
- 我不知道我的循环中怎么可能有无效的代理。
调试代码非常困难,因为我在“Agent::Step 函数”中收到内存异常(为时已晚,因为我无法理解列表中的无效代理是如何被调用的)。
当我查看 Agent::Step 函数(异常点)中的 Agent 引用时,代理中的任何数据都没有意义,甚至初始化数据也没有意义。所以肯定是无效的。
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-关于调试代码的任何建议?