QMutexLocker, QMutex C2530 references must be initialized
I have it QMutex m_mutex;
like a private field in my class and I try to block it using QMutexLocker
from one of the methods, but when I try to build it I get error C2530 (my compiler is MSVC 2015).
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
class MyClass : public QObject
Q_OBJECT
public:
MyClass(QObject *parent = 0) : QObject(parent) {}
void setValue(const SomeEnum& val)
{
QMutexLocker(&m_mutex) // C2530
m_enum = val;
}
private:
QMutex m_mutex;
SomeEnum m_enum;
};
EDIT: it works when i use &this->m_mutex
source to share
The code should be:
QMutexLocker something(&m_mutex);
which declares a named variable something
, which is QMutexLocker, and persists until the end of the block (which in this case is the end of the function).
The code QMutexLocker(&m_mutex);
is a bit annoying parsing - it follows the syntax for declaring a link, i.e. it is the same as QMutexLocker& m_mutex;
which throws an error because the links need to be initialized.
The code QMutexLocker(&this->m_mutex);
doesn't match the syntax for declaring a link, so you won't get this error. However, it creates a temporary object QMutexLocker
, which is then immediately destroyed. So, while it doesn't give a compile-time error, it probably doesn't do what you intended: the mutex will lock and then unlock before the next statement is executed.
source to share