![](/img/trans.png)
[英]move constructor/assignment of std::unique_ptr: memory reallocation?
[英]Implementing move constructor and assignment with unique_ptr<>
我的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)
使用此庫用於BTSerialPortBinding在Visual Studio 2015上的Windows 10中運行: https : //github.com/Agamnentzar/bluetooth-serial-port
unique_ptr
不能被復制,包含它的任何類都不能被復制構造或復制分配。 您將需要至少為類定義move構造函數和move賦值運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.