Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ‘m_Mutex’ declared as reference but not initialized error

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

like image 954
Yuvi Avatar asked Apr 05 '12 09:04

Yuvi


1 Answers

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.

like image 146
James Kanze Avatar answered Oct 21 '22 10:10

James Kanze