Search code examples
c++multithreadingc++11mutexstdthread

Copy constructor related compiler error


I have a resource that is shared between two concurrent threads. The resource contains a vector that both threads need to read and write to. Hence, I make access to the vector exclusive through a mutex. So far so good, sharing of resource works well without any problems.

However, the problem starts when I try to write a copy constructor for sharedResource as follows.

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 get 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 am I getting the error and if there is a way to use the mutex without getting the compiler error.

If all else fails, I am going to create a thread unsafe GetVec2 member function, that will return vec without going through lock guard. But I would like to avoid this eventuality.

std::vector<int> GetVec2() const {
    return vec;
}

Solution

  • This happens because getVec() is a const method but vecMutex is not mutable. You should either make getVec() non-const so it can modify (acquire) the mutex, or make the mutex mutable so it can be acquired by const methods too. I'd probably do the latter.