首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重载C-字符串的函数模板

重载C-字符串的函数模板
EN

Stack Overflow用户
提问于 2021-08-29 10:11:52
回答 1查看 89关注 0票数 1

以下代码片段是图书c++模板中的一个示例。我的问题是,为什么最后一行中的语句返回max (max(a,b),c)成为运行时错误。有人能给我一些提示吗?谢谢!

代码语言:javascript
复制
#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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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 *的引用。

代码语言:javascript
复制
char const * const& max (char const * const& a, char const * const& b) {
   return std::strcmp(b, a) < 0 ? a : b;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68971870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档