以下代码片段是图书c++模板中的一个示例。我的问题是,为什么最后一行中的语句返回max (max(a,b),c)成为运行时错误。有人能给我一些提示吗?谢谢!
#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
}发布于 2021-08-29 12:51:05
char const* max (char const* a, char const* b)按值返回const char *变量。然后,T const& max (T const& a, T const& b, T const& c)创建一个临时变量,该变量存储该值并返回对其的const&引用(带有T = const char *)。当分配auto m2 =时,该临时指针不存在。最有可能的是,您稍后会打印或检查该值,这会导致某种“运行时错误”。
我想,从一开始就返回对const char *的引用。
char const * const& max (char const * const& a, char const * const& b) {
return std::strcmp(b, a) < 0 ? a : b;
}https://stackoverflow.com/questions/68971870
复制相似问题