I am trying to implement Mutex lock on one of my static function of single ton class. But getting this error:
$error:‘m_Mutex’ declared as reference but not initialized
$warning:warning: unused variable ‘m_Mutex’
Here is my code snippet.
========Commondefines.h==========
/**
*@class LockBlock
*This class is used to provide Mutex Lock on thread.
*/
class LockBlock
{
public:
LockBlock(pthread_mutex_t *mutex)
{
lockMutex = mutex;
pthread_mutex_lock(lockMutex);
};
~LockBlock()
{
pthread_mutex_unlock(lockMutex);
lockMutex = NULL;
}
private:
pthread_mutex_t *lockMutex;
};
========MutexImplenation.h======
#include "CommonDefines.h"
class MutexImplementation
{
private:
static pthread_mutex_t m_Mutex ;
public:
static void commonFunction();
};
====MutexImplementation.cpp==========
// Initialize static member of class.
pthread_mutex_t MutexImplentation::m_Mutex = PTHREAD_MUTEX_INITIALIZER;
void commonFunction()
{
LockBlock(&m_Mutex); // Here I am getting this error.
}
Any help would be highly appreciated.
Thanks,
Yuvi
This is really a variant of the “most embarassing parse” problem.
You’ve not defined a
m_Mutexanywhere except as a member ofMutexImplementation, so outside ofMutexImplementation, its name isMutexImplementation::m_Mutex(and since it’s private, you can’tlegally access it). When you write:
, the compiler cannot find
m_Mutex, and so supposes that you aredefining a local variable. The parentheses are legal, but have no
effect, and the declaration is the same as:
A reference to
LockBlock, and references can only be defined if theyare initialized.
If you want a local variable, you’ll have to give it a name. And if you
want it initialized to
m_Mutex, you’ll have to makem_Mutexpublic,and specify the class name as well:
for example.