C++ 右值引用请求

标签 c++ c++11 rvalue-reference

我对右值引用感到困惑,
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;
}

最佳答案

虽然a 可能看起来像一个右值,但事实并非如此。

a 本身就是一个包含右值引用的左值。

你可以获取a的地址,但不能获取move(a)的地址。

请看一下这个article真正了解专门针对您的问题的值(value)类别。

关于C++ 右值引用请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59296568/

相关文章:

c++ - 这是确定性的步调一致吗?

c++ - 构建 std::function 的 vector 时出现编译器错误

c++ - 如何在 std::future 中使用 decltype?

c++ - 有没有办法编写一个将 l-val ref 或 r-val reference 作为输入参数的函数?

c++ - 仅使用移动语义复制对象

c++ - 如何使模板右值引用参数仅绑定(bind)到右值引用?

c++ - 在 C++ 中拟合 2d 高斯函数太慢

c++ - qtcreator 安装问题无效编码

c++ - 从 shared_ptr 获取一个元素

c++ - g++ 在 freebsd 上包含路径