为什么调用移动赋值运算符?

Why is moving assignment operator called?

在下面的代码中:

#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;
}

在表达式a = 123fo中,由于A(static_cast<int>(value));调用了值构造函数请告诉我为什么调用移动赋值运算符?是不是因为A tempObj; tempObj = A(static_cast<int>(value));我搞不懂return表达式到底发生了什么

我没有看到这里的问题。首先,在运算符“”中,您创建一个 'A' 类型的对象。然后,operator "" returns this 作为右值。因此,移动赋值被调用,因为移动赋值具有右值参数。它确保(如果可能的话)在赋值过程中尽可能少的复制。

此外,我建议在这种特殊情况下不要使用自定义 "" 运算符。您可以只添加一个采用无符号长整型参数的显式构造函数。