I was wondering how to share a mutex in one class amongst different instances of another class.
Right now, I have a class, Indexer, that has a Boost mutex and condition_variable as private member variables. I create an auto_ptr of the Indexer class in my main and pass a pointer of Indexer to instances of another class, Robot.
I do that like the following:
std::auto_ptr<Indexer> index_service(new Indexer());
Robot a(*index_service.get());
Robot b(*index_service.get());
Robot c(*index_service.get());
Robot’s constructor is:
Robot(Indexer &index_service)
{
this->index_service = index_service;
}
Robot’s header looks like:
class Robot
{
public:
Robot(Indexer &index_service);
private:
Indexer index_service;
};
However, since mutexes are noncopyable, I get an error.
I was thinking of making the mutex and condition_variable shared_ptrs but I read that this could result in unexpected behaviour.
Can someone please show me the proper/correct way to do this?
Thank you!
I’m not a C++ guru, but it seems like the unholy mix of pass by reference and pointers is trouble here.
Specifically you do this:
this->index_service = index_service;But the value is passed in as
Indexer &index_serviceAnd since the local index_service is type
Indexer index_service;I believe that the assignment implies copy.
I assume you only want one instance of the
Indexer, so you are really meaning to store a reference to it in your Robot class. To do that you would want to have your constructer take a pointer (which is what the*index_service.get()call is getting you anyway). Further you want your class variable to be a pointer type.