Search code examples
c++constantsboost-mutex

Using boost::mutex::scoped_lock inside const function


This code won't compile:

    class MyClass
    {
        boost::mutex _mutex; 

        void foo() const
        {
          boost::mutex::scoped_lock lock(_mutex);
         //critical section
        }
    }

But defining the function as non const will work fine. Please, can someone explain why? Thanks!


Solution

  • You can't lock a mutex inside a const-member function because this actually modifies the internal state of the mutex (lock is not itself a const function).

    If you want to keep the function const, you'll have to declare the mutex as mutable which is a cv-qualifier that allows const functions to modify it, i.e.

    //can now be locked (i.e. modified) by a const function
    mutable boost::mutex _mutex;
    

    Using mutable relax the const constraints on the member variable which is declared with this qualifier, that's a way to get around constness, so be careful not to abuse this. In this case, it seems reasonable because a mutex is an internal tool of your class, and does not participate in "logical constness" (as opposed to "bitwise constness").