I create a class A, and overwrite operator+ and constructor A(A&&)
, I am wondering if I call
A a, b;
A c = a + b;
Is my constructor A(A &&)
called?
I tried some code, but get very confusing results
//try2.cpp
#include <iostream>
#include <string>
using namespace std;
class A {
public:
string s;
A(A &&a) { s=std::move(a.s); cout<<"A(A &&a) called"<<endl;}
A() {}
};
A operator+(const A &a, const A &b) {
A c;
c.s=a.s+b.s;
return c;
}
int main() {
A a,b;
a.s = "123";
b.s = "456";
A c = a+b;
cout<<c.s<<endl;
return 0;
}
I used gcc 7.0: g++ -std=c++1y try2.cpp
Output is 123456
, therefore A(A &&a)
is not called
But then I change
A(A &&a) = delete;
Then compiler throws error:
try2.cpp: In function ‘A operator+(const A&, const A&)’:
try2.cpp:14:10: error: use of deleted function ‘A::A(A&&)’
return c;
^
try2.cpp:7:3: note: declared here
A(A &&a) = delete;
^
try2.cpp: In function ‘int main()’:
try2.cpp:21:11: error: use of deleted function ‘A::A(A&&)’
A c = a+b;
^
try2.cpp:7:3: note: declared here
A(A &&a) = delete;
Constructor A(A &&a)
is required. But why the previous code did not call it?