Reference: code snippet from C++ Template: The Complete Guide
// maximum of two values of any type (call-by-reference)
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a < b ? b : a;
}
// maximum of two C-strings (call-by-value)
inline char const* max (char const* a, char const* 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
}
Stated issues for above code:
The problem is that if you call max() for three C-strings, the
statement
return max (max(a,b), c); becomes an error. This is because for
C-strings, max(a,b) creates a new, temporary local value that may be
returned by the function by reference.
Question> I still don't understand the points above. Why
"you can't use the three-argument version to compute the maximum of
three C-strings"?
// Update
const int* fReturnValue(const int *i)
{
return i;
}
int main()
{
int i = 3;
const int* i4= fReturnValue(&i);
cout << &i << endl;
cout << i4 << endl;
}
Observation: both lines return the same address.
So I assume that in function fReturnValue, the function returns by value but it doesn't hurt b/c it is a pointer address. In other words, the return address is still valid.
Is that true?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…