【发布时间】:2020-11-22 01:48:19
【问题描述】:
在以下情况下,我在 Integer 类中创建了 move ctor,我希望在创建 Product 对象时默认在右值引用上调用它,但我只调用复制构造函数。 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.
}
在上述情况下,如果我在 Product 类 ctor 中使用 dId(std::move(xId)),则调用 move,我希望它应该在右值引用上默认调用。 在以下情况下,我无法避免创建 Integer 类的临时对象,有什么好的方法可以避免创建临时对象。
Product(const Integer &xId)
:dId(xId)
{
}
Product(10); // inside main
我上述问题的目的是建立我的理解,以便我可以更好地利用临时对象内存。
【问题讨论】:
-
旁注:您的班级似乎不需要
int*。考虑只使用int成员,或者std::optional<int>,如果您需要跟踪没有任何 int (现在使用nullptr)。 -
这是为了建立我对移动的理解。
标签: c++ c++11 move move-semantics move-constructor