1

I have a small template class with a non-static member of type boost::shared_mutex. Whenever I try to compile it, I get the error:

'boost::shared_mutex::shared_mutex' : cannot access private member declared in class 'boost::shared_mutex'.

boost::shared_mutex really has a private nested class shared_mutex, but I don't understand why this problem arose.

Here's my class:

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

template <typename T>
class CThreadSafeQueue
{
public:
    CThreadSafeQueue();

private:
    boost::mutex    _sharedMutex;
    std::queue<T>   _queue;
};

template <typename T>
CThreadSafeQueue<T>::CThreadSafeQueue()
{

}

The same happens with a regular `boost::mutex'.

I have another, non-template class, in which I have no problem using either mutex type.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • 3
    can you post the corresponding code. – tune2fs Nov 27 '11 at 21:39
  • What version of boost are you using? I successfully compiled the code (with instantiation of template `CThreadSafeQueue x;`) with boost 1.47.0 using compiler VC2010. – hmjd Nov 27 '11 at 21:51
  • I got compilation failure when I attempt to invoke `CThreadSafeQueue` copy constructor, as @tune2fs has already indicated. – hmjd Nov 27 '11 at 22:07

2 Answers2

3

You need to make the class noncopyable, or implement your own copy and assignment operator. boost::mutex is non copyable, therefore you get this error.

You can derive your class from boost::noncopyable, to make it noncopyable.

tune2fs
  • 7,605
  • 5
  • 41
  • 57
  • That seems to help, but now I wonder how can my other class that also uses `boost::mutex` compile successfully. I didn't override copy constructor and assignment operator in that class... – Violet Giraffe Nov 28 '11 at 14:28
  • In the worst case you can use a static mutex, this will kill your performance however, but it works. – tune2fs Nov 28 '11 at 14:37
  • Ironically, my original intent was to implement lock-free queue to avoid locking at all:) – Violet Giraffe Nov 28 '11 at 14:51
-1

Huh! The solution to my problems turned out to be very simple yet very hard to find. I was only having problems with methods declared const, because lockers are mutating mutexes. All I had to do was make it mutable.

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335