Constructor-related compiler error
I have a resource that is being shared between two parallel threads. The resource contains a vector that both threads must read and write. Hence, I am making the vector exclusive through the mutex. So far so good, resource sharing works well without issue.
However, the problem starts when I try to write a copy constructor for a sharedResource like this.
class sharedResource{
public:
sharedResource(){}
sharedResource(const sharedResource &other) {
vec = other.GetVec();
}
std::vector<int> GetVec() const {
std::lock_guard<std::mutex> lock(vecMutex); // Gives error
return vec;
}
private:
std::vector<int> vec;
std::mutex vecMutex;
};
int main()
{
sharedResource bacon1;
sharedResource bacon2 = bacon1;
return 0;
}
For this code, I am getting the error
error C2664: 'std::lock_guard<std::mutex>::lock_guard(const std::lock_guard<std::mutex> &)' : cannot convert argument 1 from 'const std::mutex' to 'std::mutex &'
Could you please explain why I am getting the error and if there is a way to use the mutex without getting a compiler error.
If all else fails, I'm going to create a thread of an unsafe GetVec2 member function that will return vec without getting past the lock guard. But I would like to avoid this possibility.
std::vector<int> GetVec2() const {
return vec;
}
source to share
The quick answer is to make it vecMutex
mutable.
mutable std::mutex vecMutex;
There is another non-standard problem in the code. Your default constructor and copies are not declared correctly. It should be like this:
sharedResource(){}
sharedResource(const sharedResource &other)
{
vec = other.GetVec();
}
You are also missing the assignment operator.
source to share