复制构造函数相关的编译错误

The*_*ere 3 c++ multithreading mutex c++11 stdthread

我有一个在两个并发线程之间共享的资源.资源包含两个线程都需要读取和写入的向量.因此,我通过互斥锁访问向量.到目前为止,资源共享工作顺利,没有任何问题.

但是,当我尝试为sharedResource编写复制构造函数时,问题就会出现,如下所示.

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;
}
Run Code Online (Sandbox Code Playgroud)

对于此代码,我收到错误

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 &'
Run Code Online (Sandbox Code Playgroud)

你能解释一下我为什么会收到错误,如果有办法使用互斥锁而不会出现编译错误.

如果所有其他方法都失败了,我将创建一个线程不安全的GetVec2成员函数,它将返回vec而不通过锁定保护.但我想避免这种可能性.

std::vector<int> GetVec2() const {
    return vec;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*nck 6

getVec()是因为是一种const方法,但vecMutex不是mutable.您应该创建getVec()非const,以便它可以修改(获取)互斥锁,或者创建互斥锁,mutable以便它也可以通过const方法获取.我可能会做后者.