gpt4 book ai didi

c++ - 为什么 decltype(auto) 在这里返回一个引用?

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:56 25 4
gpt4 key购买 nike

我想(以为)我理解autodecltype 也一样。但是,在 C++14 中,可以将诸如 decltype(auto) 之类的东西作为函数的返回类型。请考虑以下事项:

decltype(auto) foo()
{
int m = 1;
return m;
}

返回类型是int,一切都有意义。

但是,

decltype(auto) foo()
{
int m = 1;
return (m);
}

返回 int&(即对 int 的引用)。

我完全不知道为什么会这样,为什么这些括号会产生任何影响!?希望有人能对此有所启发。

PS:我还用 c++ 标记,因为检查 c++ 标记的人比 c++14 多得多。

最佳答案

7.1.6.2 [dcl.type.simple]

  1. For an expression e, the type denoted by decltype(e) is defined as follows:
    — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
    — otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
    — otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
    — otherwise, decltype(e) is the type of e.

在您的示例中,您有 return (m) 所以 e(m)。这不是未加括号的 id 表达式或类成员访问,所以我们转到第二个项目符号。它不是一个 xvalue,所以我们转到第三个项目符号。它是一个左值,所以类型是 T&,其中 Tint

关于c++ - 为什么 decltype(auto) 在这里返回一个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775103/

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