In Chapter 2 Function Template of the book C++ templates, 1st Edition, there is a code example which the book say it has problem:
#include <iostream>
#include <cstring>
#include <string>
// maximum of two values of any type (call-by-reference)
template <typename T>
inline T const& max (T const& a, T const& b)
{
printf("call 1 n");
return a < b ? b : a;
}
// maximum of two C-strings (call-by-value)
inline char const* max (char const* a, char const* b)
{
printf("call 2 %s %sn", a, b);
return std::strcmp(a,b) < 0 ? b : a;
}
// maximum of three values of any type (call-by-reference)
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
return max (max(a,b), c); // error, if max(a,b) uses call-by-value
}
int main ()
{
//::max(7, 42, 68); // OK
const char* s1 = "frederic";
const char* s2 = "anica";
const char* s3 = "lucas";
::max(s1, s2, s3); // ERROR
printf("finish");
}
I try it on compiler explorer, it can work, although there is compiler warning:
<source>:24:16: warning: returning reference to temporary [-Wreturn-local-addr]
24 | return max (max(a,b), c); // error, if max(a,b) uses call-by-value
| ~~~~^~~~~~~~~~~~~
I can’t understand what it means for “returning reference to temporary”. Does it mean max(a,b) return reference to temporary? For this example, as the passed char* pointer is always valid, any potential problem here?
Thanks