使用右值引用和自动 [英] use of rvalue reference and auto

查看:59
本文介绍了使用右值引用和自动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码,一切正常。变量d为何引用int?
发生了什么事?

Given the code below, everything works. How come that the variable d is reference to int? What is going on?

int main()
{
    int a= 10;
    int &&b = a+10; // b is int &&
    auto c =b+10; // c is int
    auto &&d = a; // d is int&
    //int &&di = a; // error, as expected
    return (0);
}


推荐答案

类型推演。在 auto& d = a; auto&&中是对非常量非易失性类型的右值引用,而 a是左值,则应用此特殊规则: a的类型视为int&而不是int。然后像往常一样,选择自动的类型与 a的类型相同,即int&。因此, auto&&的类型是int&根据bames53提到的参考折叠。

There is a special rule in type deduction. In auto &&d = a; "auto&&" is an rvalue reference to a non-const non-volatile type and "a" is an lvalue, then this special rule is applied: the type of "a" is treated as int& instead of int. Then as usual choose the type of "auto" to be identical to the type of "a", that is int&. So the type of "auto&&" is int& according to reference collapsing as mentioned by bames53.

这篇关于使用右值引用和自动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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