Reputation: 33
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.
Upvotes: 1
Views: 152
Reputation: 3672
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.
Upvotes: 2
Reputation: 2568
The line
int m = test(n);
creates a copy of the value test(n)
returns (in this case a copy of n
).
If you want a reference to the return value of test(n)
you have to use one:
int& m = test(n);
A common caveat occurs with type inference using auto
: Even in this case you would have to use
auto& m = test(n);
Upvotes: 4