bug修复,内存释放问题

原文地址: https://www.ningto.com/post/5aaf87c843bef42108349a5b

碰到了一个内存释放的问题,在进行某个复杂的操作时内存释放后否则会造成崩溃。经过多方面调查发现此时根据就不能释放内存(历史原因),否则会造成不可预知的问题。所以我打算把要删除的指针暂时保存起来,并不立马delete,等到10秒钟还没有操作的时候(稍微空闲)再把保存的指针都销毁掉。

后来顺利的解决了问题,而且改动较小。

代码如下:

class DelayDestory : public QObject {
	Q_OBJECT
public:
	static DelayDestory* instance();
	void deleteItem(TreeItem *item);
	void deleteItem(const QList<TreeItem*> &items);

private slots:
	void onTimer();

private:
	DelayDestory();

private:
	static const int INTERVAL_SECOND = 5;
	static const int TIMEOUT_SECOND = 10;
	QList<TreeItem*> items_;
	class QTimer *timer_;
	QMutex mutex_;
	qint64 lastTime_;
};
DelayDestory* DelayDestory::instance()
{
	static DelayDestory s_inst;
	return &s_inst;
}

void DelayDestory::deleteItem(TreeItem *item)
{
	if (!item) {
		return;
	}

	lastTime_ = QDateTime::currentMSecsSinceEpoch();
	QMutexLocker lock(&mutex_);
	if (!items_.contains(item)) {
		items_.push_back(item);
	}
}

void DelayDestory::deleteItem(const QList<TreeItem*> &items)
{
	if (items.isEmpty()) {
		return;
	}

	lastTime_ = QDateTime::currentMSecsSinceEpoch();
	QMutexLocker lock(&mutex_);
	for (int i = 0; i < items.size(); i++) {
		if (items[i] && !items_.contains(items[i])) {
			items_.push_back(items[i]);
		}
	}
}

DelayDestory::DelayDestory()
	: mutex_(QMutex::Recursive), lastTime_(0)
{
	timer_ = new QTimer(this);
	connect(timer_, SIGNAL(timeout()), this, SLOT(onTimer()));
	timer_->start(INTERVAL_SECOND * 1000);
}

void DelayDestory::onTimer()
{
	qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
	if (currentTime - lastTime_ >= TIMEOUT_SECOND * 1000 && !items_.isEmpty()) {
		QList<TreeItem*> tempList;
		{
			QMutexLocker lock(&mutex_);
			tempList = items_;
			items_.clear();
		}
		qDebug() << "delete tree items, size:" << tempList.size();
		for (int i = 0; i < tempList.size(); i++) {
			delete tempList[i];
		}
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值