原文解释是说 c-strings 这种重载返回了一个局部变量的引用,便随着 stack unwinding 被回收了。
但是没有明白为什么这段代码会产生一个局部变量的引用,恳请 v 站各位大侠帮忙指点,多谢~
return max (max(a,b), c); becomes a run-time error because for C-strings, max(a,b) creates a new, temporary local value that is returned by reference, but that temporary value expires as soon as the return statement is complete, leaving main() with a dangling reference. Unfortunately, the error is quite subtle and may not manifest itself in all cases.
Note, in contrast, that the first call to max() in main() doesn ’ t suffer from the same issue. There temporaries are created for the arguments (7, 42, and 68), but those temporaries are created in main() where they persist until the statement is done.
代码如下
#include <cstring> // maximum of two values of any type (call-by-reference) template<typename T> T const& max (T const& a, T const& b) { return b < a ? a : b; } // maximum of two C-strings (call-by-value) char const* max (char const* a, char const* b) { return std::strcmp(b,a) < 0 ? a : b; } // maximum of three values of any type (call-by-reference) template<typename T> 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 () { auto m1 = ::max(7, 42, 68); // OK char const* s1 = "frederic"; char const* s2 = "anica"; char const* s3 = "lucas"; auto m2 = ::max(s1, s2, s3); //run-time ERROR } 