Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use macro in the class declaration

Tags:

c++

leveldb

I am reading the source code of leveldb, esp. regarding mutexlock.

I found this declaration:

class SCOPED_LOCKABLE MutexLock {
 public:
  explicit MutexLock(port::Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu)
      : mu_(mu)  {
    this->mu_->Lock();
  }
  ~MutexLock() UNLOCK_FUNCTION() { this->mu_->Unlock(); }

 private:
  port::Mutex *const mu_;
  // No copying allowed
  MutexLock(const MutexLock&);
  void operator=(const MutexLock&);
};

and I found that SCOPED_LOCKABLE is defined as empty, so why use it in the class declaration?

like image 736
storm Avatar asked Oct 05 '22 00:10

storm


1 Answers

In class or function definitions if developer need to attach extra characteristic it uses MACROS than hard coding in each class or function definitions. This is a good practice for programming. because one day if you need to change this characteristic you have to change in only one place not everywhere of the code.

Some usage of macros in class definition

#ifdef CONTROLLER_EXPORTS
   #define CONTROLLER_API __declspec(dllexport)
#else
   #define CONTROLLER_API __declspec(dllimport)
#endif

class CONTROLLER_API CConfiguration{
} ;

You can get some more windows related useful clues here. http://msdn.microsoft.com/en-us/library/dabb5z75(v=vs.80).aspx

Even you can use access modifiers also like this, because some time for testing you may need to change the access level temporary.

#define PRIVATE private
#define PUBLIC public

class A{
PRIVATE:
  int m_a;
PUBLIC:
  int m_b;
}

Then what is exact your issue? it can be any useful characteristic define like above. here is one example i got from git

#define SCOPED_LOCKABLE     __attribute__ ((scoped_lockable)) 
  • For details about __attribute__ check here
  • For the source I got above code check here
like image 178
Nayana Adassuriya Avatar answered Oct 28 '22 11:10

Nayana Adassuriya