c++ - 自身模板崩溃原因

标签 c++ qt templates crash qvector

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

#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。

提前致谢!

最佳答案

添加这个方法:

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

解释:

T r() const 返回 r_ 的拷贝。然后被摧毁。而实际的 r_ 并没有在此处修改 test2.r().resize(10);。稍后。

关于c++ - 自身模板崩溃原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30757238/

相关文章:

c++ - libssh2 远程 ncurses 应用程序

c++ - 有什么方法可以从 C++ 中的成员指针类型派生对象类型

javascript - 在 Django 模板中包含 JavaScript 的最佳实践

c++ - 为什么 libcxx 中的 __dependent_type 使用模板非类型参数 bool _Dummy?

c++ - 为什么 ostream iomanip 在传递给操作符 << 时不需要模板参数?

c++ - QSqlquery prepare() 和 bindvalue() 不工作?

c++ - 为什么我收到错误消息 : "restrict" not allowed?

c++ - QT中QAudioInput bufferSize()和bytesReady()的关系

c++ - 如何解决错误 "o rule to make target"?

c++ - QList takeLast() 和 removeLast() 冲突