warning: returning reference to temporary

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.


Solution 1:

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.

Solution 2:

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.