我目前在处理包含对象 vector 的类的析构函数时遇到问题。应用程序运行良好,但在释放堆时会引发错误。
这是我的析构函数的代码:
~StaticNetwork(void) { // clear memory
for(vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); )
nodes.erase(iter++);
}
节点被添加到网络中如下:
if((temp = is_already_added(regex_d[1])) >= 0) // check if the src node has already been added
{
if((temp1 = is_already_added(regex_d[2])) >= 0) // check if the next_hop has already been added
{
nodes[temp]->add_n_vchannels(regex_d[5]);
nodes[temp]->add_next_hop(nodes[temp1]);
}
else // the next_hop has not been added
{
Node *anext_hop = new Node(regex_d[2]);
nodes[temp]->add_next_hop(anext_hop);
nodes[temp]->add_n_vchannels(regex_d[5]);
nodes.push_back(anext_hop); // add next hop
param.n_of_nodes++;
}
}
网络由指向实际节点的指针组成。
任何帮助/建议/引用/(建设性)批评将不胜感激。
最佳答案
您对容器的迭代是错误的。如果 node
是类的成员,则忽略它,因为 vector 的析构函数会处理它。如果它不是成员并且你真的想删除所有元素,最简单的方法是调用 node.clear()
(注意两者等同于你的代码,但如果它会泄漏指向的内存应该由你的类(class)管理)
如果指针由您的类管理,请考虑使用智能指针或特定指针容器。否则,释放所有内存的最简单循环是:
for ( std::vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); ++it )
delete *it;
请注意,我没有修改容器本身,只是修改了包含的元素。
关于c++ - vector 迭代器不兼容 : runtime error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968120/