0

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?

  • How do you compile this program? Here, it is fairly obvious copies can be elided, so most compilers will do so. – Nelewout May 21 '21 at 17:34
  • [Return Value Optimization / Copy Elision.](https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization) – ChrisMM May 21 '21 at 17:34

0 Answers0