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_Mutex
anywhere except as a member of
MutexImplementation
, so outside of MutexImplementation
, its name is
MutexImplementation::m_Mutex
(and since it's private, you can't
legally access it). When you write:
LockBlock (&m_Mutex);
, the compiler cannot find m_Mutex
, and so supposes that you are
defining a local variable. The parentheses are legal, but have no
effect, and the declaration is the same as:
LockBlock& m_Mutex;
A reference to LockBlock
, and references can only be defined if they
are 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 make m_Mutex
public,
and specify the class name as well:
LockBlock& localRefToMutex( &MutexImplementation::m_Mutex );
for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With