【发布时间】:2012-10-14 08:28:45
【问题描述】:
我正在尝试从 Java 适应 C++,但当我从 STL priority_queue 中 pop() 一个项目时,我不确定管理内存的正确方法。
我是否应该使用 delete 来清理从队列中删除的不再需要的项目?如果是这样,怎么做?如果没有,为什么不呢?
我自己写了一个小程序来学习如何使用priority_queue(代码如下)。在这个程序中,内存泄漏没什么大不了的,因为它的规模很小,而且结束得很快。但是我想学习正确的做事方式,这样我就可以编写一个正确处理更大队列而不会发生内存泄漏的程序。
我不明白的是:top() 返回的是引用而不是指针。但是我不能在引用上使用 delete,可以吗?
有人可以在这里指出正确的方向吗?
--------
struct PathCost{
int dest;
int cost;
PathCost(int _dest, int _cost){
dest = _dest;
cost = _cost;
}
bool operator<(PathCost other) const;
bool operator>(PathCost other) const;
};
bool PathCost::operator<(PathCost other) const{
return cost < other.cost;
}
bool PathCost::operator>(PathCost other) const{
return cost > other.cost;
}
int main(){
PathCost pc = PathCost(1, 2);
pc = PathCost(3, 4);
PathCost* pcp = new PathCost(5, 6);
delete pcp;
priority_queue<PathCost,
vector<PathCost>,
greater<vector<PathCost>::value_type> > tentativeQ;
cout << "loading priority queue ...\n";
tentativeQ.push(PathCost(8, 88));
tentativeQ.push(PathCost(5, 55));
tentativeQ.push(PathCost(7, 77));
tentativeQ.push(PathCost(4, 44));
cout << "\nlist items on queue in priority order ...\n";
while (!tentativeQ.empty()){
pc = tentativeQ.top();
cout << "dest:" << pc.dest << " cost:" << pc.cost << endl;
tentativeQ.pop();
/* DO I NEED TO DO MEMORY CLEANUP AT THIS POINT? */
}
}
【问题讨论】:
-
简而言之,没有。您的变量都是自动的。每次弹出都会从队列顶部删除一个项目并适当地销毁它。一般来说,如果你不
new或malloc某事,你不必担心deleteing 或freeing 它(strdup() 等无法承受)。 -
谢谢。这很有帮助。我知道我有一些 Java 思维要忘掉。
-
很高兴它有帮助。 Juanchopanza 的答案是正确的,顺便说一句,如果你对它感到满意,应该这样标记。 (旁边的绿色小勾号)。
标签: c++ memory-leaks stl priority-queue