Crash cause of own template

63 views Asked by At

why is my program crashing when I use my template? What I'm doing wrong? That's a test program, because the actual program is too big for posting here. The first qDebug with test1 are displayed but the second not.

#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();
}

I'm using Qt 5.4 on MS Vista.

Thanks in advance!

1

There are 1 answers

0
Amartel On BEST ANSWER

Add this method:

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

Explanation:

T r() const returns a copy of r_. Which is destroyed then. While actual r_ is not modified here test2.r().resize(10);. And later on.