Search code examples
c++rvalue-reference

C++ why int rvalue reference changed in this example?


#include <iostream>
using namespace std;

int&& a(int&& b) {
    cout << b << endl; //output 5
    return std::move(b);
}

string&& d(string&& e) {
    cout << e << endl; //output abc
    return std::move(e);
}
int main() {
    // your code goes here
    int&& b = a(5);
    cout << b<< endl; // output 0
    string&& f = d("abc");
    cout << f << endl; //output abc
    return 0;
}

The function a should return an rvalue reference to 5. Why is value of b changed after the move? while the string f is unchanged?


Solution

  • Quoting Remy's answer from https://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary.

    "- a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference."

    Both temporary objects are destroyed at the end of the full expression. The behavior is totally undefined here for both the int&& and string&&.