I'm trying to figure out rvalue and lvalue categories and can't understand this example:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Vec {
string name;
public:
Vec(string name) : name(name) {
cout << "Created "<< name <<"\n";
}
Vec(const Vec &a) {
name = a.name;
name[0]++;
cout << a.name << " copied in "<< name <<"\n";
}
Vec(Vec &&a) noexcept {
swap(name, a.name);
cout << "Moved " << name << "\n";
}
~Vec() {
cout << "Destroyed "<< name <<"\n";
}
};
void bar(Vec &&a) {
cout << "rvalue func\n";
}
Vec a("a");
Vec foo() {
Vec b = a;
return b;
}
int main() {
bar(foo());
cout << "End of main()\n";
}
Output:
Created a a copied in b rvalue func Destroyed b End of main() Destroyed a
In the foo function, the variable b is an lvalue, and when it is returned as the result of the function, I expect that a temporary copy will be created. But for some reason, b becomes an rvalue and moves to the bar function without copying. Can someone explain to me what is going on in this code?