[英]Move constructor should be called by default
在以下情況下,我在 Integer class 中創建了移動 ctor,我希望在創建產品 object 時默認在右值引用上調用它,但我只調用構造函數。 Gcc - Ubuntu 18 上的 7.5.0
#include<iostream>
using namespace std;
class Integer
{
int *dInt = nullptr;
public:
Integer(int xInt) {
dInt = new int(xInt);
cout<<"Integer Created"<<endl;
}
Integer(const Integer &xObj)
{
cout<<"Copy called"<<endl;
dInt = new int(xObj.mGetInt());
}
Integer(Integer &&xObj)
{
cout<<"Move called"<<endl;
dInt = xObj.dInt;
xObj.dInt = nullptr;
}
Integer& operator=(const Integer &xObj)
{
cout<<"Assignment operator called"<<endl;
*dInt = xObj.mGetInt();
return *this;
}
Integer& operator=(Integer &&xObj)
{
cout<<"Move Assignment operator called"<<endl;
delete dInt;
dInt = xObj.dInt;
xObj.dInt = nullptr;
return *this;
}
~Integer()
{
cout<<"Integer destroyed"<<endl;
delete dInt;
}
int mGetInt() const {return *dInt;}
};
class Product
{
Integer dId;
public:
Product(Integer &&xId)
:dId(xId)
{
}
};
int main ()
{
Product P(10); // Notice implicit conversion of 10 to Integer obj.
}
在上述情況下,如果我在產品 class ctor 中使用 dId(std::move(xId)) ,則調用移動,我期望它應該在右值引用上默認調用。 在以下情況下,我無法避免創建臨時 object 的 Integer class,有什么好方法可以避免創建臨時 ZA8CFDE6331BD4B862AC9.
Product(const Integer &xId)
:dId(xId)
{
}
Product(10); // inside main
我上述問題的目的是建立我的理解,以便我可以更好地利用臨時 object memory。
您需要std::move
來“傳播”右值引用。
主體內部如下 function:
void foo(int&& x);
…表達式x
是一個左值int
。 不是int&&
。
引用並不真正“存在” ——即使它們由類型系統提供支持,它們也應該被視為別名(而不是單獨的實體),因此在foo
中使用x
就像使用原始的、被引用的一樣對待如您所知, int
inside foo
... 並且這樣做也會創建一個副本。
這將完成這項工作:
Product(Integer&& xId)
: dId(std::move(xId))
{}
但是,我實際上鼓勵您按價值取Integer
:
Product(Integer xId)
: dId(std::move(xId))
{}
這樣,您也可以使用相同的構造函數來傳遞左值Integer
,如果需要,將生成一個副本,而如果沒有,則會自動發生移動(例如,通過傳入文字,這將自動觸發選擇Integer
的移動構造函數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.