Flurite wrote: |
---|
"Passing a temporary object to a function works perfectly by const reference, and gives you know warnings. However, when I try to return a temporary object as a const reference, the compiler throws a warning.
Why is this?" |
Because you're returning a temporary object. Consider this example:
This creates a temporary, unnamed
int variable with the value of 10. The temporary object is bound to
Temp_, and will have the same life-span as
Temp_. When you use a reference to a constant as a return-type, you'll either be returning a temporary object, or a local object (bad):
1 2 3 4 5 6 7
|
int const &Function()
{
// ...
int X_;
// ...
return(X_);
}
|
X_ is bound to the returned reference, but since
X_ is local to
Function(),
X_ will be destroyed as soon as
Function() ends. When the call ends, the reference too is destroyed, unless you claim its value, but such a thing is dangerous.
I recommend not return a reference to any local object, even if its a reference to a constant. However, if you declare a local static object, it'll be safe to return the static object, because its life-time matches that of the program's. For example:
1 2 3 4 5
|
int const &Function()
{
static int Value_(10);
return(Value_); // OK.
}
|
Wazzak