优先队列自定义对象动态申请问题

本文通过一个C++代码示例,展示了在使用优先队列时,若析构函数中包含`delete`操作可能导致的问题。当对象被push进优先队列并进行比较时,析构函数可能会被多次调用,从而触发已删除空间的错误。代码中创建了一个包含析构函数的`Node`类,并在析构函数中尝试删除内存。由于`priority_queue`的性质,导致析构函数被不正确地调用,引发错误。解决这个问题需要重新考虑对象生命周期和内存管理策略。

在使用优先队列是,不能申请空间,因为每次push进一个对象都会和之前的比较并且调用一次析取函数。而如果析取函数里有delete语句,就会造成delete已删除空间的问题。

会报这个报错

测试代码奉上,各位感兴趣可尝试 

#include<iostream>
#include<queue>
using namespace std;
int cnt = 0;
int n, k;
class Node {
	int* t;
	int max;
public:
	void Update(int* a) {
		memcpy(t, a, k * sizeof(int));
		for (int i = 1; i < k; i++)
			if (max < t[i])
				max = t[i];
	}
	int GetMax() const{
		return max;
	}
	Node() {
		t = new int[k];
		max = -INT_MAX;
		cnt++;
		cout << "构造"<<cnt << endl;
	}
	~Node() {
		//delete[] t;
		cout << "析构"<<t[0] << endl;
	}
	bool operator >(const Node& n) const{
		return max > n.max;
	}
	bool operator <(const Node& n) const {
		return max < n.max;
	}
};
int main() {
    k=1;
	priority_queue<Node> Q; 
	int *tmp = new int[k];
	Node n1, n2, n3;
	n = 3;
	tmp[0] = 1;
	n1.Update(tmp);
	tmp[0] = 2;
	n2.Update(tmp);
	tmp[0] = 3;
	n3.Update(tmp);
	cout << "push n1" << endl;
	Q.push(n1);
	cout << "push n2" << endl;
	Q.push(n2);
	cout << "push n3" << endl;
	Q.push(n3);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值