mardi 30 juin 2020

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.

Aucun commentaire:

Enregistrer un commentaire