I wrote a program as below:
#include <iostream>
using namespace std;
class A {
public:
A() {
}
A(A &a) {
id = a.id;
cout << "copy constructor" << endl;
}
A& operator=(A &other) {
id = other.id;
cout << "copy assignment" << endl;
return *this;
}
A(A &&other) {
id = other.id;
cout << "move constructor" << endl;
}
A& operator=(A &&other) {
id = other.id;
cout << "move assignment" << endl;
return *this;
}
public:
int id = 10;
};
A foo() {
A a;
return a;
}
int main()
{
A a;
A a2(a); // output: copy constructor
A a3 = a2; // output: copy constructor
a3 = a2; // output: copy assignment
A a4 = foo(); // output:
a4 = foo(); // output: move assignment
return 0;
}
I compiled it on my Mac OS. The output is:
copy constructor
copy constructor
copy assignment
move assignment
My question are:
- Why the output of
A a4 = foo();
is empty? I thought it should call the move constructor. - Why the output of
A a3 = a2;
iscopy constructor
instead ofcopy assignment
?