【发布时间】:2013-02-21 21:37:43
【问题描述】:
参考:C++ 模板中的代码 sn-p:完整指南
// 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-strings, max(a,b) 创建一个新的临时本地值,它可能是 由函数通过引用返回。
问题> 我还是不明白以上几点。为什么
"你不能使用三参数版本来计算最大值 三个 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,它是一个指针地址。也就是说,返回地址仍然有效。
这是真的吗?
【问题讨论】:
-
据我所知,strcmp 不是 std 命名空间的一部分...
-
@thang:是的,是的。
-
@thang:
cstring我猜? en.cppreference.com/w/cpp/string/byte/strcmp -
cstring 是包含文件吗?哪个 c++ 标准?
-
@thang:
cstring是一个包含文件,当然,任何 C++ 标准。从 C 标准库继承的所有类型和函数都存在于全局命名空间和std命名空间中。
标签: c++