gpt4 book ai didi

c++ - 在哪些情况下,编译器会在比较两种类型时创建一个新的临时局部值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:57:47 25 4
gpt4 key购买 nike

template <typename T> inline T const& max (T const& a, T const& b) 
{
return a < b ? b : a;
}

inline char const* max (char const* a, char const* b)
{
return std::strcmp(a,b) < 0 ? b : a;
}

template <typename T> inline T const& max (T const& a, T const& b, T const& c)
{
return max (max(a,b), c);
}

int main ()
{
const char* s1 = "frederic";
const char* s2 = "anica";
const char* s3 = "lucas";

::max(s1, s2, s3);
}

对于上面的代码,书(C++ Templates - Wesley)说:

The problem is that if you call max() for three C-strings, the statement return max (max(a,b), c); 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.

现在,我的问题是在哪些情况下编译器会自动创建并返回临时变量,为什么(包括这个)?

哦!这是否意味着编译器创建一个临时变量来存储每个值,然后返回那些比较过的临时变量?还有其他情况吗?

最佳答案

让我们慢慢来:

::max(s1, s2, s3);

调用 T const& max (T const& a, T const& b, T const& c)T正在char const* .

在这个方法中我们有:

max(a,b)

调用 char const* max (char const* a, char const* b)

max(max(a,b), c);

因此调用char const* max (char const* a, char const* b)还有

因此可怕的部分(如果我们重写):

template <typename T>
T const& max (T const& a, T const& b, T const& c)
{
T result = max(max(a,b), c);
return result; // reference to a temporary
}

因为 Tchar const*max(char const*, char const*)返回(指针的)拷贝而不是指针的 const 引用。

gcc有助于诊断问题(请参阅 ideone ):

prog.cpp: In function ‘const T& max(const T&, const T&, const T&) [with T = const char*]’:
prog.cpp:27: instantiated from here
prog.cpp:18: warning: returning reference to temporary

18正在return max(....)在模板和27作为调用。

如果重写max “隐藏”这个临时的:

template <typename T> inline T const& max (T const& a, T const& b, T const& c)
{
T const& result = max (max(a,b), c);
return result;
}

您将阻止 gcc 的检测(参见 ideone ),但这并不能解决问题。 Clang 会很有帮助地警告 T const& result绑定(bind)到一个临时的。

真正的问题是 char const* max(char const*, char const*)正在返回一个值,所以要么全部 max应该按值或全部返回 max应该获取并返回 const 引用......如果你想把它们混在一起。

关于c++ - 在哪些情况下,编译器会在比较两种类型时创建一个新的临时局部值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7283214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com