参考资料:来自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()函数,语句
return max (max(a,b), c);会出错。这是因为对于C字符串,max(a,b)会创建一个新的、临时的局部值,可能被引用返回。
问题> 我还是不理解上面的观点。为什么不能使用三个参数的版本来计算三个C字符串的最大值?
"你不能使用三个参数的版本来计算三个C-strings的最大值"的原因是什么?
// 更新
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中,该函数按值返回但不会有害,因为它是指针地址。换句话说,返回的地址仍然有效。 这是真的吗?
cstring
吧?http://en.cppreference.com/w/cpp/string/byte/strcmp - K-ballocstring
是一个头文件,可以在任何 C++ 标准中使用。所有从 C 标准库继承的类型和函数都同时存在于全局命名空间和std
命名空间中。 - K-ballo