Why does decltype(auto) return a reference here?

↘锁芯ラ 提交于 2019-11-30 11:02:41

问题


I think (thought) I understand auto. Same about decltype. However, in C++14, one can have some diabolic 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.


回答1:


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.



来源:https://stackoverflow.com/questions/27557369/why-does-decltypeauto-return-a-reference-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!