tags:

views:

769

answers:

4

I have a function like this

const string &SomeClass::Foo(int Value)
{
    if (Value < 0 or Value > 10)
        return "";
    else
        return SomeClass::StaticMember[i];
}

I get warning: returning reference to temporary. Why is that? I thought the both values the function returns (reference to const char* "" and reference to a static member) cannot be temporary.

+3  A: 

The problem is in the first line. "" will be turned into an std::string, as it has a valid constructor that takes a char*. That std::string will be an anonymous object, which is temporary, and you return its reference.

Shaggy Frog
+1  A: 

Like Shaggy Frog said, it converts "" to a temporary std::string object and since your method signature is std::string& it attempts to return a reference to it, hence you get the warning. One workaround may be to return the std::string by value (const std::string SomeClass::Foo(..)).

ttvd
+13  A: 

This is an example when an unwanted implicit conversion takes place. "" is not a std::string, so the compiler tries to find a way to turn it into one. And by using the string( const char* str ) constructor it succeeds in that attempt. Now a temporary instance of std::string has been created that will be deleted at the end of the method call. Thus it's obviously not a good idea to reference an instance that won't exist anymore after the method call. I'd suggest you either change the return type to const string or store the "" in a member or static variable of SomeClass.

Christian
A good answer! Here's why i think C++ is not a good choice for nowadays programming challenges. It'll consume you time taking care about its inner works when you would prefer to focus in the problem at hands.
Luis Filipe
@Luis: Every language you care to mention has these corner case gotchas.
Martin York
It would appear the conversion *is* wanted here! :P Once you change to returning by value, the const should be dropped too.
Roger Pate
+1  A: 

This is the exemplary of trying to optimize code in c++. I did it, everybody did it... It is worth mentioning that this is the classical example that is eligible to return value optimization.

Like ttvd said the correct answer is to return const std::string and not a reference to it and to let the compiler optimise it.

If you trust the interpreter of your favorite language to optimize behind you, you shouldn't try to be too smart with C++ either.

Emmanuel Caradec