这个例子来自Josuttis的C++ templates一书:
#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
}他说,::max(s1, s2, s3)中出现错误的原因是,对于C字符串,max(max(a,b),c)调用max(a,b),这会创建一个新的临时本地值,该值可能会由函数通过引用返回。
我不明白一个新的本地价值是如何创造的?
发布于 2012-02-09 14:33:02
对于C字符串,此代码创建一个局部值,即存储地址的局部变量( char const *类型的指针):
std::strcmp(a,b) <0?B: a;
因此,返回对this的引用(使用模板函数)会导致错误。在本例中,模板函数max在C字符串max返回副本后返回对local类型的char const * const &引用。模板函数必须按值而不是按引用返回指针。
需要为指针类型重载模板函数。
https://stackoverflow.com/questions/9206319
复制相似问题