使用boost :: mutex - 隐式删除错误(因为默认定义不正确)

Sah*_*wal 1 c++ boost

我在.h文件中有类看起来如下(标题)

#include <boost/thread.hpp>

class MyClass{

    private:
        boost::mutex bPoolMtx_;

        // ... other vars
    public:
        // public vars and methods

}
Run Code Online (Sandbox Code Playgroud)

尝试构建/编译时出现以下错误.

MyClass.h:38:7: note: ‘MyClass::MyClass(const MyClass&)’ is implicitly deleted because the default definition would be ill-formed:
MyClass.h:38:7: error: use of deleted function ‘boost::mutex::mutex(const boost::mutex&)’
Run Code Online (Sandbox Code Playgroud)

我还没有在cpp文件中使用互斥锁.当我注释掉它的boost::mutex线条时它很好.到底是怎么回事?

aco*_*mar 5

默认情况下,编译器生成的默认复制构造函数会复制所有数据成员.您的使用会boost::mutex引发错误,因为互斥锁不可复制.

您可以编写自己的复制构造函数,不会尝试复制互斥锁或只删除复制构造函数MyClass.

#include <boost/thread.hpp>

class MyClass{
    private:
        boost::mutex bPoolMtx_;

        // ... other vars
    public:
        // public vars and methods
        MyClass(const MyClass&) = delete;
}
Run Code Online (Sandbox Code Playgroud)