使用unique_ptr<>

时间:2016-04-23 16:39:27

标签: c++ move-semantics unique-ptr move-constructor

我的Device.cpp文件中有当前的构造函数

Device::Device(const char *devName)
{
    device = devName;
    bt.reset(BTSerialPortBinding::Create(devName, 1));
}

我的Device.h包含一个类设备:

Device(const char *devName="");
~Device();
const char *device;
std::unique_ptr<BTSerialPortBinding> bt;

我正在尝试右移移构造函数并移动赋值,因为unique_ptr不可复制,因此我的类变为不可复制,并且~Device()最终删除它。

因此当我尝试使用时:

Device dev; // declared in Process.h

dev = Device("93:11:22"); // initialised in Process.cpp

我收到以下错误:

Device &Device::operator =(const Device &)': attempting to reference a deleted function

我在Device.h中尝试了以下但没有运气:

//move assignment operator
Device &operator=(Device &&o)
{
    if (this != &o)
    {
        bt = std::move(o.bt);
    }
    return *this;
}
Device(Device &&o) : bt(std::move(o.bt)) {};

我在尝试时遇到这些错误:

1>bluetoothserialport.lib(BTSerialPortBinding.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MTd_StaticDebug' in ArduinoDevice.obj
1>bluetoothserialport.lib(BluetoothHelpers.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MTd_StaticDebug' in ArduinoDevice.obj
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "public: __thiscall std::_Lockit::_Lockit(int)" (??0_Lockit@std@@QAE@H@Z) already defined in libcpmtd.lib(xlock.obj)
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "public: __thiscall std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in libcpmtd.lib(xlock.obj)
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "void __cdecl std::_Debug_message(wchar_t const *,wchar_t const *,unsigned int)" (?_Debug_message@std@@YAXPB_W0I@Z) already defined in libcpmtd.lib(stdthrow.obj)
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "void __cdecl std::_Xbad_alloc(void)" (?_Xbad_alloc@std@@YAXXZ) already defined in libcpmtd.lib(xthrow.obj)
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "void __cdecl std::_Xlength_error(char const *)" (?_Xlength_error@std@@YAXPBD@Z) already defined in libcpmtd.lib(xthrow.obj)
1>msvcprtd.lib(MSVCP140D.dll) : error LNK2005: "void __cdecl std::_Xout_of_range(char const *)" (?_Xout_of_range@std@@YAXPBD@Z) already defined in libcpmtd.lib(xthrow.obj)

在Visual Studio 2015上的Windows 10中运行,使用此库进行BTSerialPortBinding:https://github.com/Agamnentzar/bluetooth-serial-port

1 个答案:

答案 0 :(得分:0)

unique_ptr无法复制,任何包含它的类都无法复制构造或复制分配。您至少需要为您的类定义移动构造函数和移动赋值运算符。