欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

bug修复,内存释放问题

最后更新 2018-03-19 09:50:00   阅读量 2364

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

下一篇 – Qt自定义Tooltip
上一篇 – bug修复,解决延迟搜索的问题

  1. C/C++
  2. Qt

toningto@outlook.com

标签云

IOS Qt Life Linux Java MongoDB Boost MQ Node.js Mac C/C++ Tools Design Python Bug Others Javascript Tips React Android Web Mobile Shell Product Go Database Windows

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2