简体   繁体   English

移动分配运算符未被调用

[英]Move assignment operator not being called

I've just been doing some exercises with move semantic, and I can't seem to figure out why my move assignment operator is not being called 我刚刚使用move语义进行了一些练习,但似乎无法弄清楚为什么未调用我的move赋值运算符

My class is as follows (please ignore any bad practice that is not relevant to the question): 我的课程如下(请忽略与该问题无关的任何不良做法):

private:
    int sz;
    double* elems;

public:
    Vector(int size):sz(size), elems(new double[size])
    {
         for(int i=0; i!=sz; ++i)
         {
             elems[i] = i;
         }
    }

    ~Vector()
    {
         std::cout << "Destruct " << std::endl; delete [] elems;
    }

    double& operator[](int i)
    {
        return elems[i];
    }
    const double& operator[](int i)const 
    {
         return elems[i];
    }

    //operator+ to add vectors
    friend Vector operator+(const Vector& a, const Vector& b)
    {

        Vector ret(a.sz);
        if(a.sz!=b.sz)
            return 0;
        std::cout << "Adding" << std::endl;
        for(int i=0; i!=a.sz; ++i)
        {
            ret[i] = a[i] + b[i];
        }

        return ret;
     }

     //move constructor
     Vector(Vector&& a): sz(a.sz),elems(a.elems)
     {
          std::cout << "Move constructor"<< std::endl;
          a.elems = nullptr;
          a.sz = 0;
     }

     //move assignment
     Vector& operator=(Vector&& a)
     {
        std::cout << "Moveeee" << std::endl;
        delete [] elems;
        elems = a.elems;
        sz = a.sz;
        a.elems = nullptr;
        a.sz = 0;

        return *this;
     }

Now my test case is as follows: 现在我的测试用例如下:

Vector v1(3);
Vector v2(3);
Vector v3(3);
Vector v4 = v1+v2;

The output is as follows: 输出如下:

Adding
Move constructor
Destruct
Destruct
Destruct
Destruct
Destruct

What I expect is line Vector v4 = v1+v2; 我期望的是行Vector v4 = v1+v2; to call the move assignment, but it doesn't. 调用移动分配,但是没有。 Instead it calls the move constructor. 而是调用move构造函数。

I even tried Vector v4 = std::move(v2); 我什至尝试了Vector v4 = std::move(v2); , but that also didn't work and called the move constructor. ,但这也不起作用,因此将其称为move构造函数。

Any idea why the move assignment is not being called? 知道为什么不调用移动分配吗?

Semantically you are not calling assignment 语义上您不是在打电话给作业

Vector v4 = v1+v2;

is really: 是真的:

Vector v4(v1+v2);

If there is no copy constructor, but a default constructor and an acceptable assignment exists, then assignment will be called. 如果没有复制构造函数,但是存在默认构造函数和可接受的分配,则将调用分配。 As commented you would need to do: 如所评论,您需要执行以下操作:

Vector v4; v4 = v1 + v2;

to have a true assignment 有一个真正的任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM