Reputation: 201
In this code:
const int & fun(const int &i)
{
return 2*i;
}
int main()
{
const int k=3;
cout<<fun(k)<<endl;
return 0;
}
In this case the parameters of fun
are not local (No Temporary object made to store the Reference return type) then why this warning?
+ If I remove const from the return type of function fun it says
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
But on removing 2* (only i left as value being returned) it doesn't show any error -> What I can think is this 2* thing is converting the return into Rvalue but then isn't the return value an Rvalue itself? Where am I going wrong?
Upvotes: 1
Views: 620
Reputation: 180500
return 2*i;
does not multiply 2
by i
and store that result into i
. It multiples 2
by i
and puts that result into a temporary. Trying to return that temporary by reference is a no go as it is destroyed at the end of that line. lifetime extension does not apply here.
If you want to modify i
and return it you need to use operator *=
which will modify i
and give you a reference to it that you can return like
return i *= 2;
But fun
would need to take a int&
instead of const int &
.
If you want to return an rvalue then what you do is return by value like:
int fun(const int &i)
{
return 2*i;
}
and now you can capture it like:
int main()
{
const int& ret = fun(3);
cout << ret << endl;
return 0;
}
Upvotes: 5