为什么 decltype(auto) 在这里返回一个引用? [英] Why does decltype(auto) return a reference here?

查看:36
本文介绍了为什么 decltype(auto) 在这里返回一个引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

decltype(auto) foo(){整数 m = 1;返回 m;}

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

然而,

decltype(auto) foo(){整数 m = 1;返回(米);}

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

我完全不知道为什么会发生这种情况,为什么这些括号有任何区别!?希望有人能对此有所了解.

PS:我也用 c++ 标记了,因为检查 c++ 标记的人比 c++14 多.

解决方案

7.1.6.2 [dcl.type.simple]

<块引用>

  1. 对于表达式e,decltype(e)所表示的类型定义如下:
    — 如果 e 是无括号的 id 表达式或无括号的类成员访问 (5.2.5),则 decltype(e) 是由 e 命名的实体的类型.如果没有这样的实体,或者如果 e 命名了一组重载函数,则程序格式错误;
    — 否则,如果 e 是 xvalue,则 decltype(e) 是 T&&,其中 T 是 e 的类型;
    — 否则,如果 e 是左值,则 decltype(e) 是 T&,其中 T 是 e 的类型;
    — 否则,decltype(e) 是 e 的类型.

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

I think (thought) I understand auto. Same about decltype. However, in C++14, one can have some thing like decltype(auto) as the return type of a function. Consider the following:

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

The return type is int, everything makes sense.

However,

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

returns int& (i.e. reference to int).

I have absolutely NO IDEA why this happens, why do these parentheses make any difference at all!? Hope someone can shed some light on this.

PS: I've also tagged with c++ as there are many more people that check the c++ tag than 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.

In your example you have return (m) so e is (m). That is not an unparenthesized id-expression or class member access, so we go to the second bullet. It is not an xvalue so we go to the third bullet. It is an lvalue, so the type is T& where T is int.

这篇关于为什么 decltype(auto) 在这里返回一个引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆