【问题标题】:Move constructor should be called by default默认情况下应调用移动构造函数
【发布时间】: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&lt;int&gt;,如果您需要跟踪没有任何 int (现在使用nullptr)。
  • 这是为了建立我对移动的理解。

标签: c++ c++11 move move-semantics move-constructor


【解决方案1】:

您需要 std::move 来“传播”右值引用。

在以下函数体内:

void foo(int&& x);

...表达式x 是一个左值int不是 int&amp;&amp;.

引用并不真正“存在”——即使它们由类型系统提供支持,它们也应该被视为别名(而不是单独的实体),因此在内部使用 x foo 的处理方式与在 foo 中使用原始的、引用的 int 一样……这样做会创建一个副本,如您所知。


这样就可以了:

Product(Integer&& xId)
    : dId(std::move(xId))
{}

但是,我实际上鼓励您按价值接受Integer

Product(Integer xId)
    : dId(std::move(xId))
{}

这样,您也可以使用相同的构造函数来传递左值Integer,并且会生成一个副本如果需要,而如果没有,则会自动进行移动(例如,通过传入字面量,这将自动触发选择Integer的移动构造函数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2016-06-17
    • 2012-10-17
    • 2021-05-14
    相关资源
    最近更新 更多