Search code examples
c++11returnmove

Why is moving assignment operator called?


In the following code:

#include <bits/stdc++.h>

using namespace std;

class A {
public:
    A(const A& a) noexcept { cout << "copy constructor" << endl; }
    A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; return *this;}
    A(A&& a) noexcept { cout << "move constructor" << endl; }
    A& operator=(A&& a) noexcept { cout << "move assignment operator" << endl; return *this;}

    A() { cout << "default constructor" << endl; }
    A(int val) { cout << "value constructor" << endl; }

private:
    int value;
};

A operator"" fo(unsigned long long value)
{
    return A(static_cast<int>(value));
}

int main()
{
    A a;       // default constructor
    A b = a;   // copy constructor
    b = a;     // copy assignment operator
    a = 123fo; // value constructor, move assignment operator
    return 0;
}

In the expression a = 123fo, value constructor is called because of A(static_cast<int>(value)); Please tell me why move assignment operator is called? Is it because A tempObj; tempObj = A(static_cast<int>(value)); I can't figure it out what exactly happened in the return expression.


Solution

  • I don't see the problem here. First, in operator "", you create construct an 'A' type object. Then, operator "" returns this as an rvalue. And so, the move assignement is called, as the move assignments has the rvalue parameter. It ensures that (if possible), there is as few copying during the assignment as possible.

    Also, I would recommend to not to use a custom "" operator in this particular case. You could just add an explicit constructor taking an unsigned long int parameter.