bug修复,内存释放问题

Table of Contents

    碰到了一个内存释放的问题,在进行某个复杂的操作时内存释放后否则会造成崩溃。经过多方面调查发现此时根据就不能释放内存(历史原因),否则会造成不可预知的问题。所以我打算把要删除的指针暂时保存起来,并不立马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];
    		}
    	}
    }