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

标签 c++ multithreading c++11 mutex stdthread

我有两个并发线程共享的资源。该资源包含两个线程都需要读取和写入的 vector 。因此,我通过互斥锁来独占访问 vector 。到目前为止一切顺利,资源共享运行良好,没有任何问题。

但是,当我尝试如下为 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;
}

对于这段代码,我得到错误

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 &'

能否请您解释一下为什么我会收到错误消息,以及是否有一种方法可以在不收到编译器错误的情况下使用互斥锁。

如果一切都失败了,我将创建一个线程不安全的 GetVec2 成员函数,它将返回 vec 而不通过锁守卫。但我想避免这种情况。

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

最佳答案

发生这种情况是因为 getVec() 是一个 const 方法,但 vecMutex 不是 mutable。您应该将 getVec() 设置为非 const,以便它可以修改(获取)互斥量,或者将互斥量设置为 mutable,以便它也可以通过 const 方法获取。我可能会选择后者。

关于c++ - 复制构造函数相关的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26921534/

相关文章:

c++ - .template (dot-template) 构造用法

c++ - doxygen 方程显示不正确

c++ - SDK 指针问题 - C++ 到 Delphi 的翻译

c++ - 使用线程编程时出现 std::thread::_Invoker 错误

java - 方法减慢执行 paintComponent()

templates - 部分专门化类模板以将 boost::tuple 作为参数之一时出错

c++ - 'Constexpr' 与 'extern const' 对比。哪个优先?

c++ - boost 如何知道要链接哪个 LIB 以及如何更改它?

c++ - 值得产生一个新线程的最小工作量

c++ - 使用用户定义的比较类对 std::pair 的 std::vector 进行排序