在我的代码中,我没有故意为 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 中定义我自己的复制构造函数和一个空的主体来解决这个问题。
但是,我仍然不确定为什么我必须在一种情况下创建自己的复制构造函数,并且能够通过编译器生成的另一种情况来解决。罪魁祸首当然是互斥体。是创建此问题的互斥锁的不可复制属性还是我缺少的其他东西?