代码来自 C++ templates 第二版:
#include <cstring>
#include <iostream>
using std::cout;
using std::endl;
// maximum of two values of any type (call-by-reference)
template <typename T>
T const &max(T const &a, T const &b)
{
cout << "T const &max(T const &a, T const &b) called" << endl;
return b < a ? a : b;
}
// maximum of two C-strings (call-by-value)
char const *max(char const *a, char const *b)
{
cout << "char const *max(char const *a, char const *b) called" << endl;
cout << a << endl;
cout << b << endl;
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()
{
char const *s1 = "frederic";
char const *s2 = "anica";
char const *s3 = "lucas";
auto m2 = ::max(s1, s2, s3); // run-time ERROR
//!!! m2 已经是一个 dangling reference ,但是仍然得到预期结果?
cout << m2 << endl;
}
不理解的地方在最后一行,m2 已经是一个 dangling reference ,但是为什么输出仍然得到预期结果?
编译使用的是 g++:
$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.31.1)
Target: x86_64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
编译输出:
$ g++ test2.cpp -o test2 -std=c++11
test2.cpp:28:12: warning: returning reference to local temporary object [-Wreturn-stack-address]
return max(max(a, b), c); // error if max(a,b) uses call-by-value
^~~~~~~~~~~~~~~~~
test2.cpp:36:17: note: in instantiation of function template specialization 'max<const char *>' requested here
auto m2 = ::max(s1, s2, s3); // run-time ERROR
^
1 warning generated.
运行结果:
char const *max(char const *a, char const *b) called
frederic
anica
char const *max(char const *a, char const *b) called
frederic
lucas
lucas
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.