I have a class with a mutex in it:
Class StoreNumbers{
StoreNumbers();
AddNumber(size_t number){
const std::lock_guard<std::mutex> lock(lock_);
numbers_.push_back(number);
}
private:
std::mutex lock_;
std::vector<size_t> numbers_;
};
The purpose of the class is to be able to store numbers while used in a multithreaded context. There is certainly better ways to do that but that illustrates my question.
Now I want to have various objects of these classes, in order to store different types of numbers. I also want each of these types to have a different mutex, since they are unrelated.
If I write:
std::vector<StoreNumbers> vec;
vec.push_back(StoreNumber());
I get the compiler error: no matching function for call to 'construct_at', which I understand since the mutex is non copyable.
If instead I use:
std::unique_ptr<std::mutex> lock_=std::make_unique<std::mutex>();
for the lock and dereference it for the lock_guard, I do not get the error anymore. I do not understand why. Thanks for the help!