【问题标题】:Implementing move constructor and assignment with unique_ptr<>使用 unique_ptr<> 实现移动构造函数和赋值
【发布时间】:2016-04-23 16:39:26
【问题描述】:

我的 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

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

  • 我试图定义一个移动构造函数和赋值 - 我已经编辑了我的帖子,但我收到了 LINK 错误(可以在编辑后的帖子中看到)
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 2019-05-17
  • 2013-06-11
  • 2020-03-22
  • 2020-08-03
  • 1970-01-01
  • 2021-05-31
相关资源
最近更新 更多