Warning: returning temporary reference (from constant)

Good morning: the situation is this:

.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 these two functions using

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

Now the compiler gives me a warning for

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

Well, I know, in theory, why I get this warning: when I use the temporary link. It's great. However, I do not understand why const int zero_int; considered temporary.

Thanks for any clarification.

Edit : as suggested in the comment, I edited the class & null template. Although initially I could not include the error code (because the error message is a function), I cleaned it up to publish it here and efficiently in the process, I understood the cause of the error. In particular:

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

An error occurs when in a line of code I call

 zero<long long int>() 

which, in fact, creates a temporary. Attempt:

 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 β€œsmall” problem (namely: the result is not 0, but some random number is probably associated with other bytes that the program reads)

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

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

Thus, you get a complete error, for example:

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

which will remind me when I should determine the right specialization.

Thanks for pointing me in the right direction.

+5
source share

Source: https://habr.com/ru/post/1272010/


All Articles