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;
}

      

+3


source to share


2 answers


This is because it getVec()

is const

, but vecMutex

it is not mutable

. You must either make a getVec()

non-const so that it can modify (acquire) the mutex, or make a mutex mutable

so that it can be obtained by const methods as well. I will probably do the latter.



+6


source


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.

+4


source







All Articles