Search code examples
c++referencereturn-value

return reference in cpp function returns a copy


I am trying to return the reference of the argument in the function test, but when I assign another value to the returned reference, the original doesn't change:

#include <iostream>

using namespace std;

int& test(int& n) {
    return n;
}

int main() {
    int n = 1;
    int m = test(n);
    m = 2;
    cout << n << endl; // n = 1
    return 0;
}

How can I return this reference as I expect?

This testing is just for studying purposes.


Solution

  • Make m an lvalue reference:

     int& m = test(n);
    

    You can also bind to temporaries like this:

    int test(int& n) { // return by value
        return n;
    }
    
    int main() {
        int n = 1;
        int&& m = test(n); // rvalue reference binding to a copy of `n`
        m = 2;
        std::cout << n << std::endl;
        return 0;
    }
    

    Although the above code is not recommended.

    Or even this:

    int&& test( int& n ) // return by rvalue reference
    {
        return std::move( n ); // cast `n` from lvalue to xvalue
    }
    
    int main( )
    {
        int n = 1;
        int&& m = test(n);
        m = 2;
        std::cout << n << std::endl;
    }
    

    This one is also not recommended. Instead of rvalue reference, you should return by value.