1

I have class looks as follows in .h file (Header)

#include <boost/thread.hpp> class MyClass{ private: boost::mutex bPoolMtx_; // ... other vars public: // public vars and methods } 

I get the following error trying to build/ compile.

MyClass.h:38:7: note: ‘MyClass::MyClass(const MyClass&)’ is implicitly deleted because the default definition would be ill-formed: MyClass.h:38:7: error: use of deleted function ‘boost::mutex::mutex(const boost::mutex&)’ 

I don't use the mutex at all in the cpp file yet. When I comment out the boost::mutex line it builds fine. What is going on?

2
  • 4
    It means the mutex is not copyable. You are probably copying MyClass instances somewhere. This requires the data members to be copyable. Commented Apr 28, 2014 at 19:25
  • Exactly. Try to disable copying for MyClass, and see what happens then. Commented Apr 28, 2014 at 19:26

1 Answer 1

6

The default copy constructor generated by the compiler copies all data members by default. Your use of boost::mutex throws an error because the mutex isn't copyable.

You can write your own copy constructor that doesn't attempt to copy the mutex or simply delete the copy constructor for MyClass.

#include <boost/thread.hpp> class MyClass{ private: boost::mutex bPoolMtx_; // ... other vars public: // public vars and methods MyClass(const MyClass&) = delete; } 
Sign up to request clarification or add additional context in comments.

6 Comments

Does this mean I cannot copy MyClass if I want to use mutex? for example having a vector<MyClass> somewhere?
You need to write your own copy constructor that copies the data but constructs a new mutex.
I see. Appreciate your response, I fixed it now by storing a pointer instead since the copying was not needed. Thanks
"Appreciate your response, I fixed it now by storing a pointer instead since the copying was not needed." - 8-| ... danger lurks.
Using a pointer means that the copy and the original will lock on the same mutex (i.e., when a method call on the original takes the mutex, all internally synchronized method calls on the copy will block too). That's probably not a good idea.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.