参考:来自C++模板的代码片段:完整指南
// 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(),则语句 返回最大值( max (a,b),c);成为错误。这是因为对于C-字符串,max(a,b)创建一个新的临时本地值,该值可能由函数引用返回。
Question>,我仍然不明白上面的要点。为什么
“您不能使用三个参数版本来计算三个C-字符串的最大值”?
//最新情况
const int* fReturnValue(const int *i)
{
return i;
}
int main()
{
int i = 3;
const int* i4= fReturnValue(&i);
cout << &i << endl;
cout << i4 << endl;
}注意:两行都返回相同的地址。因此,我假设在函数fReturnValue中,函数按值返回,但它不损害b/c --它是一个指针地址。换句话说,返回地址仍然有效。
这是真的吗?
发布于 2013-02-20 20:50:27
问题是,max的C-字符串风格是按值返回的,而不是按值取其参数。一般的3路max函数被声明为返回一个引用,但是C-字符串max返回一个值,这将导致返回一个临时的引用,这个临时引用在您访问它之前就已经死了。
更新:您添加的新代码并不等同于您原来的问题。这将:
const int*& fReturnValue(const int *i)
{
return i;
}注意,fReturnValue返回对局部变量i的引用,该变量的生存期在函数返回时结束。因此,该函数返回对无效对象的引用。试着用这种方法编译代码,几乎每个编译器都会发出警告。
https://stackoverflow.com/questions/14989564
复制相似问题