John Yang John Yang - 1 month ago 5
C++ Question

error: no matching function for call to 'boost::shared_lock<boost::shared_mutex>::shared_lock(const Lock&)'

I have implemented a ReadLock like following:

In my myClass.h

#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>

typedef boost::shared_mutex Lock;
typedef boost::shared_lock< Lock > ReadLock;

Lock myLock;


In myClass.cpp:

void ReadFunction() const
{
ReadLock r_lock(myLock); // Error!
//Do reader stuff
}


The code works in VS2010 but failed with GCC4.0. The compiler is throwing error at ReadLock saying there is no matching function. I suspect is the "const" correctness problem with the variable myLock. When I removed the const in the function declaration, the error disappeared. Can anybody explain this to me? Why this works under windows but not with gcc?

Any suggestion here? Thanks.

Answer

You should either remove the const qualifier from ReadFunction(), because qualifying a non-member function with cv or ref qualifiers is illegal and doesn't even makes sense; or you encapsulate whatever you are trying to do in a class.


void ReadFunction() const
{
    ReadLock r_lock(myLock); // Error!
    //Do reader stuff
}

const can only be applied to member functions. The above code isn't a member function, if it was, it would be, (for example, a class named MyClass):

void MyClass::ReadFunction() const
{
    ReadLock r_lock(myLock);
    //Do reader stuff
}

And in that case, you would typically need to make lock a mutable member. by declaring it like this:

class MyClass{
    ....
    mutable Lock myLock;
};