Search code examples
c++pthreadsconst-correctness

C++ Const correctness in C wrapper class


Could somebody please give me a little advice regarding const correctness within a C++ wrapper class which encapsulates some legacy C functionality.

Given the following class which partially wraps the pthread mutex API:

class Mutex {
private:
  pthread_mutex_t mMutex;

public:
  Mutex();
  void lock();
  void unlock();
  bool tryLock(); };

Should the member variable mMutex and the lock(), unlock() and tryLock() methods be declared as const? From a C++ perspective, whilst none of these methods actually change the value of the object, they do appear to change the encapsulated state.

Conceptually, should "const" apply to an object's value, state or both?


Solution

  • As far as I can tell all three functions in <pthread.h> take pthread_mutex_t* arguments. NOT pthread_mutex_t const* arguments.

    So purely from the technical perspective you already have to make your three member functions non-const as a const member function will have access to this as Mutex const and its member variable mMutex as pthread_mutex_t const. Taking its pointer will then require a const_cast breaking const correctness.


    But even if this wasn't the case, it wouldn't seem right to have a function with heavy side effects that can be called from a context that promised not to change the object.

    So, in any case, your member functions aren't const.