我在实现具有map<int,list<Arestas*>>.
的类的析构函数时遇到问题
我的地图将如下所示:
key list
[1] - [2,10] -> [3,100] -> [4,25]
[2] - [1,10] -> [3,50]
[3] - [2,50] -> [1,100] -> [4,40]
[4] - [1,25] -> [3,40]
我的Arestas类包含:
class Arestas {
private:
Fronteira *vertice;
unsigned int custo;
}
我的析构函数现在看起来像这样:
for (auto it = myGrafo.begin(); it != myGrafo.end(); ++it) {
for (auto it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1) {
delete *it1;
}
(*it).second.clear();
}
但是当我从key [2]中查找列表时,却给了我这个错误:
_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block) noexcept
{
#ifdef _DEBUG
_free_dbg(block, _UNKNOWN_BLOCK);
#else
free(block);
#endif
}
提前谢谢!
编辑
我将Arestas*
插入地图:
Arestas *aux = new Arestas();
aux->setCusto(_custo);
aux->setVertice(encontrarFronteira(vertice_destino));
// Se o vertice nao existir
if (aux->getVertice()->getVertice() == NULL) {
cout << "ERROR" << endl;
exit(1);
}
myGrafo[vertice_origem].push_back(aux);
// Put the same path in the opposite vertice
Arestas *aux1 = new Arestas();
// set cost
aux1->setCusto(_custo);
// it looks for the vertice in the list<vertices*>
aux1->setVertice(encontrarFronteira(vertice_origem));
myGrafo[vertice_destino].push_back(aux1);
答案 0 :(得分:2)
似乎您对结构的所有权有疑问。您在列表中多次拥有这些aresta,并且多次删除它们是未定义的行为,因此您只需删除一次即可。
尝试这样的事情:
std::set<Arestas*> s;
for(const auto& p1: m)
{
for(const auto& el: p1.second)
{
s.insert(el);
}
}
因此,您将创建一组需要删除的所有元素。然后删除它们(也可以使用唯一的指针,实际上是更好的解决方案)。
for(auto p: s)
{
delete p;
}
看来您的Arestas可能是唯一的,所以如果在vertice
上共享并销毁这些问题,问题可能出在Arestas析构函数上。
答案 1 :(得分:1)
首先,您只能delete
个先前用new
语句创建的对象。
如果是这样,为了避免多次删除操作,可以使用std::shared_ptr<Aresta>
之类的智能指针。
您可以使用Valgrind执行代码以获取有关此问题的更具体的信息。