C ++右值引用请求

问题描述 投票:1回答:2

我对右值引用感到困惑,is_rvalue_reference<decltype(a)>::value表示a变量是右值参考,但无法将其传递给hello(int &&)函数。

#include <iostream>
#include <string>
#include <array>
using std::cout;
using std::endl;
using std::boolalpha;
using std::string;
using std::is_rvalue_reference;
using std::move;


void hello(int && z) {};


int main(void) {
    int && a = 20;

    // a is_xvalue: true
    cout << "a is_xvalue: " << boolalpha << is_rvalue_reference<decltype(a)>::value << endl;

    // error C2664:  
    // 'void hello(int &&)': cannot convert argument 1 from 'int' to 'int &&'
    hello(a);       

    // compile ok.
    hello(move(a));

    return 0;
}
c++ c++11 rvalue-reference
2个回答
2
投票

[Typesvalue categories是两个独立的事物。

每个C ++表达式(具有其操作数,文字,变量名等的运算符)的特征在于两个独立的属性:typevalue category

a的类型是int&&,即右值参考。但是a作为命名变量,是左值,不能绑定到右值引用。似乎令人困惑,但请尝试将它们分开考虑。

(重点是我的)

以下表达式是左值表达式:

  • 变量的名称,函数,模板参数对象(自C ++ 20起)或数据成员,无论类型如何,例如std :: cin或std :: endl。 即使变量的类型是右值引用,由名称组成的表达式是左值表达式;

1
投票

虽然a看起来好像不是r值。

a本身就是一个包含r值引用的l值。

您可以使用a的地址,但不能使用move(a)的地址。

[请查看此article,以真正理解专门针对您的问题的价值类别。

© www.soinside.com 2019 - 2024. All rights reserved.