【问题标题】:Crash cause of own template自己的模板崩溃原因
【发布时间】:2015-06-10 13:05:21
【问题描述】:

为什么我在使用模板时程序会崩溃?我做错了什么? 那是一个测试程序,因为实际程序太大,无法发布 这里。 显示第一个 qDebugtest1,但第二个不显示。

#include <QCoreApplication>
#include <QDebug>
#include <QMutex>

class MutexLocker {
public:
    MutexLocker(QMutex& m) : _m(m) { _m.lock(); }
    ~MutexLocker() { _m.unlock(); }

private:
    QMutex& _m;
};

template<typename T>
class ThreadGuard {
public:
    ThreadGuard() { _mutex = new QMutex(); }

    ~ThreadGuard() { delete _mutex; }

    void set(const T& other) {
        MutexLocker m(*_mutex); Q_UNUSED(m);
        _r = other;
    }

    void set(int i, int j) {
        MutexLocker m(*_mutex); Q_UNUSED(m);
        _r[i] = j;
    }

    T r() const {
        MutexLocker m(*_mutex); Q_UNUSED(m);
        return _r;
    }

    const ThreadGuard<T>& operator=(const T& other) {
        set(other);
        return *this;
    }

private:
    ThreadGuard(const ThreadGuard&) {}

    T _r;
    QMutex *_mutex;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QVector<int> test1(10);

    for(int i = 0; i < 10; i++){
        test1[i] = i*2;
    }
    for(int i = 0; i < 10; i++){
        qDebug() << test1[i];
    }

    ThreadGuard<QVector<int> > test2;
    test2.r().resize(10);

    for(int i = 0; i < 10; i++){
        test2.r()[i] = i*2;
    }
    for(int i = 0; i < 10; i++){
        qDebug() << test2.r()[i];
    }


    return a.exec();
}

我在 MS Vista 上使用 Qt 5.4。

提前致谢!

【问题讨论】:

  • test2.r() 返回一个副本
  • 你为什么使用自己实现的 MutexLocker 而不是提供的 QMutexLocker?

标签: c++ qt templates crash qvector


【解决方案1】:

添加这个方法:

T & r() {
    MutexLocker m(*_mutex); Q_UNUSED(m);
    return _r;
}

解释:

T r() const 返回r_ 的副本。然后被摧毁。虽然实际r_ 未在此处修改test2.r().resize(10);。以后再说。

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多