【发布时间】:2012-01-13 20:43:45
【问题描述】:
我正在尝试在 C++ 中实现有向图。但是,我的 RemoveEdge 函数出现问题,在我调用该函数并在指针上使用 delete 运算符并将指针设置为 nullptr 之后,它不会在函数范围之外为空。
我不确定我是否已经足够清楚地说明了我的问题,但也许一些代码会有所帮助。
Graph.h
template<class TVertex, class TEdge, class TWeight>
class Graph
{
protected:
std::list<Vertex<TVertex, TEdge, TWeight>*>* _Vertices;
std::list<Edge<TVertex, TEdge, TWeight>*>* _Edges;
public:
Graph();
int TotalVertices();
int TotalEdges();
std::list<Vertex<TVertex, TEdge, TWeight>*>* Vertices();
std::list<Edge<TVertex, TEdge, TWeight>*>* Edges();
Vertex<TVertex, TEdge, TWeight>* FindVertex(const TVertex&);
Vertex<TVertex, TEdge, TWeight>* InsertVertex(const TVertex&);
void RemoveVertex(const TVertex&);
Edge<TVertex, TEdge, TWeight>* FindEdge(const TEdge&);
Edge<TVertex, TEdge, TWeight>* InsertEdge(const TVertex&, const TVertex&, const TEdge&, const TWeight&);
void RemoveEdge(const TEdge&);
};
Graph.FindEdge()
template<class TVertex, class TEdge, class TWeight>
Edge<TVertex, TEdge, TWeight>* Graph<TVertex, TEdge, TWeight>::FindEdge(const TEdge& label)
{
Edge<TVertex, TEdge, TWeight>* edge = nullptr;
std::list<Edge<TVertex, TEdge, TWeight>*>::iterator it;
for(it = this->_Edges->begin(); it != this->_Edges->end(); ++it)
{
if(label == (*it)->Label())
{
edge = *it;
break;
}
}
return edge;
}
Graph.RemoveEdge()
template<class TVertex, class TEdge, class TWeight>
void Graph<TVertex, TEdge, TWeight>::RemoveEdge(const TEdge& label)
{
Edge<TVertex, TEdge, TWeight>* edge = this->FindEdge(label);
if(edge == nullptr)
return;
this->_Edges->remove(edge);
edge->Source()->RemoveEdge(edge);
edge->Destination()->RemoveEdge(edge);
// Problem is here, why isn't this working like I think it should?
delete edge;
edge = nullptr;
}
Main.cpp
// created graph
// added vertices
// added edges
Edge<string, string, int>* e5 = graph->InsertEdge("Oshawa", "Toronto", "E5", 5);
graph->RemoveEdge("E5");
cout << ((e5 == nullptr) ? "null" : "not null") << endl; // this outputs not null
所以你可以看到我的程序在我从图中删除边缘后崩溃,由于某种原因它在执行 RemoveEdge 函数后输出not null。我不确定为什么会发生这种情况,我使用了 delete 运算符,并且之后我还明确地使指针为空。我在这里做错了什么?
是的,我确定找到了边缘,FindEdge 函数找到了正确的边缘对象并将其从适当的列表中删除,但删除操作符没有做我想做的事情。
感谢任何帮助。提前致谢。
【问题讨论】:
-
edge 似乎是一个局部变量,它在“空”后立即超出范围。你能从 FindEdge() 中获得对指针的引用吗?
-
嗯,我不确定你的意思。这不是使用指针的意义吗,这样我就不必担心范围,因为它指向内存位置?你能举个例子说明你的意思吗?
-
int x = 5; int* xp1 = &x; int* xp2 = xp1; xp2 = nullptr;。在这段代码中,xp1 不会是空指针
标签: c++ pointers null-pointer delete-operator