【发布时间】:2013-07-20 18:45:10
【问题描述】:
我有一个模拟程序。在模拟的主类中,我正在“创建+添加”和“删除+销毁”代理。
问题是有时(我每运行程序 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- 对调试代码有什么建议吗?
【问题讨论】: