使用 unique_ptr<> 实现移动构造函数和赋值

Implementing move constructor and assignment with unique_ptr<>

本文关键字:移动 构造函数 赋值 实现 gt ptr unique lt 使用      更新时间:2023-10-16

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

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

My Device.h 包含一个类 Device 具有:

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

unique_ptr不能

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