我正在尝试从 Java 适应 C++,当我从 STL priority_queue 中弹出()项目时,我不确定管理内存的正确方法。
我是否应该使用 delete 来清理从队列中删除的不再需要的项目?如果是这样,怎么做?如果不是,为什么不呢?
我给自己写了一个小程序来学习如何使用priority_queue(代码如下)。在这个程序中,内存泄漏没什么大不了的,因为它的规模很小,而且结束得很快。但是我想学习正确的做事方式,这样我就可以编写一个程序来正确处理更大的队列而不会出现内存泄漏。
我不明白的是:top() 返回的是引用而不是指针。但是我不能在引用上使用删除,可以吗?
有人可以在这里指出我正确的方向吗?
--------------------
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? */
}
}