Warning: returning reference to temporary (from a const)

Viewed 185

Good morning: the situation is as follows

.h file

extern const std::string void_string_;
extern const int zero_int;

template <typename Class>    
inline const Class& zero() 
{
   // an error message
}

template <>
inline const int& zero<int>()
{
    return zero_int;
}

template <>
inline const std::string& zero<std::string>()
{
    return void_string_;
}

.cpp file

const std::string void_string_="";
const int zero_int=0;

Then I call this two functions using

zero<int>()
zero<string>()

Now, the compiler give me a warning for

zero<int>()
Warning: returning reference to temporary

Ok, I know, in theory, why I get that warning: when I use a reference to a temporary. That's fine. Still I don't get why the const int zero_int; is considered temporary.

Thanks for any clarification.

Edit: as suggested in a comment, I edited the Class& zero template. While initially I couldn't include the error code (because the error message is a function), I cleaned it to post it here and effectively in the process I understood the reason of the error. Specifically:

template <typename Class>    
inline const Class& zero() 
{
    std::cout << "No!" << std::endl; // substitutes the original error message
    return zero_int;
}

The error happens when in a line of the code, I call

zero<long long int>() 

which, effectively, creates a temporary. Trying:

template <typename Class>    
inline const Class& zero() 
{
    std::cout << "No!" << std::endl; // substitutes the original error message
    return (Class&)zero_int;
}

removes the warning, but obviously gives another 'little' problem (namely: the result is not 0, but some random number, probably related to the other bytes the program reads)

At this point the only change I did was to leave Class& zero() undefined.

template <typename Class>    
inline const Class& zero(); // left undefined by purpose

In this way a get a full error, like:

undefined reference to `long long const& zero<long long>()'

which will remind me when I have to define the correct specialization.

Thanks for pointing me in the right direction.

0 Answers
Related