Passing and returning a temporary object

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?

In my case, I have a function that finds something. It returns what it finds. The problem is is that it might not find anything, so returning a temporary object was my initial solution. However, with this warning I am afraid it might cause problems. Any other ideas?
Last edited on
closed account (zb0S216C)
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:

 
int const &Temp_(10);

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
@Framework

I want to learn more about these, where can do that? What should I look for?
Last edited on
Oh okay, thanks.
closed account (zb0S216C)
@ToniAz: I recommend reading Scott Meyers' "Effective C++", and "More Effective C++" books. Also, I recommend reading these: http://www.parashift.com/c++-faq-lite/

Wazzak
Topic archived. No new replies allowed.