【问题标题】:Copy constructor required to be explicity defined with mutex需要使用互斥锁显式定义的复制构造函数
【发布时间】:2015-06-10 07:27:11
【问题描述】:

在我的代码中,我没有故意为 Complex 和 Composition 类定义复制构造函数。我希望使用编译器提供给我的复制构造函数

#include<boost/make_shared.hpp>
#include<boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

class Complex
{ 
  private : 
  std::string _a;
  std::string _b;
};

class Composition
{
  public:
    Composition(){}
    Composition(int x, int y)
    {
      _x = x;
      _y = y;
    }
  private:
    int _x;
    int _y;
    Complex obj;
};

int main()
{
  //Used make_shared this way on purpose
  boost::shared_ptr<Composition> ptr = boost::make_shared<Composition>(Composition(1,2) );
}

上面的代码编译没有任何问题。

现在我将复杂类更改为跟随

class Complex
{
  private : 
  std::string _a;
  std::string _b;
  boost::mutex _mutex;
};

当我编译代码时,我得到了错误

/usr/local/include/boost/smart_ptr/make_shared.hpp:660: error: no matching function for call to ‘Composition::Composition(const Composition&)’
note: candidates are: Composition::Composition(int, int)
note:                 Composition::Composition()
note:                 Composition::Composition(Composition&)

我已经通过在 Composition 中定义我自己的复制构造函数来解决这个问题,现在它是一个空的主体。

然而,我仍然不确定为什么我必须在一种情况下创建自己的复制构造函数,并且能够通过编译器生成的另一种情况来解决。罪魁祸首当然是互斥体。是创建此问题的互斥锁的不可复制属性还是我缺少的其他东西?

【问题讨论】:

    标签: c++ boost shared-ptr copy-constructor default-copy-constructor


    【解决方案1】:

    来自this页面

    类互斥体

    mutex 类是 Mutex 和NonCopyable 的模型,不提供 超出这些概念要求的附加设施。

    因为boost::mutex 是NonCopyable,如果您的类包含/继承它作为成员,编译器将不会生成复制构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 2015-10-31
      • 2012-02-23
      • 2013-11-17
      相关资源
      最近更新 更多