c++ - Crash cause of own template -
why program crashing when use template? i'm doing wrong? that's test program, because actual program big posting here. first qdebug
test1
displayed 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 = 0; < 10; i++){ test1[i] = i*2; } for(int = 0; < 10; i++){ qdebug() << test1[i]; } threadguard<qvector<int> > test2; test2.r().resize(10); for(int = 0; < 10; i++){ test2.r()[i] = i*2; } for(int = 0; < 10; i++){ qdebug() << test2.r()[i]; } return a.exec(); }
i'm using qt 5.4 on ms vista.
thanks in advance!
add method:
t & r() { mutexlocker m(*_mutex); q_unused(m); return _r; }
explanation:
t r() const
returns copy of r_
. destroyed then. while actual r_
not modified here test2.r().resize(10);
. , later on.
Comments
Post a Comment