为了更多地了解C++模板,我读了一本书(C++模板:补语指南),无法理解解释。
// basics/max3a.cpp
#include <iostream>
#include <cstring>
#include <string>
// 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
}书上说,
“问题是,如果为三个C-字符串调用max(),则语句
return max (max(a,b), c);变成一个错误。这是因为对于C-字符串,max(a,b)创建一个新的临时本地值,该值可能由函数引用返回。
“
我知道max(s1,s2,s3)是由引用参数调用的,但是在三个函数的最大值内,max(a,b)使用的是按值调用函数(因为它更具体)。并且临时返回值max(a,b)是一个值(在堆栈中),并且没有max(值、引用)函数。这不是问题所在吗?我听不懂书上写着... 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的文字。
发布于 2017-08-21 00:28:29
临时返回值max(a,b)是一个值(在堆栈中)。
不,返回值不是“在堆栈中”。这是一种价值,时期。句号:
inline char const* max (char const* a, char const* b)这将返回一个值。在调用者的上下文中,它是一个临时值。现在,让我们继续下一步:
return max (max(a,b), c); //在这个模板中,这个return返回一个引用。参考值是对max()调用返回的值,在此上下文中,该值是一个临时值。
此临时值超出作用域,并在此函数调用返回时被销毁。并返回对已销毁值的引用。取消引用此引用将成为未定义的行为。
这与模板和专业化无关。对于同等的、非模板代码也是如此。
https://stackoverflow.com/questions/45787824
复制相似问题