I would like to doublecheck my understanding of move semantics. Am I missing anything in my reasoning:
#include <iostream>
using std::cout;
struct A
{
A() {cout<<"Constructor\n";}
~A() {cout<<"Desctuctor\n";}
A(const A&) {cout<<"Copy Constructor\n";}
A(A&&) noexcept {cout<<"Move Constructor\n";}
int x{1};
};
int f1(A a)
{
cout<<"f1(A a)\n";
return a.x;
}
int f2 (A&& a)
{
cout<<"f2 (A&& a)\n";
return a.x;
}
int main()
{
A a1, a2;
f1(std::move(a1));
f2(std::move(a2));
}
Output:
Constructor
Constructor
Move Constructor
f1(A a)
Desctuctor
f2 (A&& a)
Desctuctor
Desctuctor
From what I can see with f2()
, I'm not creating any additional copies, even "light" move copies, which is cool.
So my understanding now is that if I'm going to use move semantics, I better always write functions/methods signature to accept r-values as to avoid any unnecessary copies at all. Or there is something else I'm missing ?