【问题标题】:Function doesn't takes Rvalue reference as parameter? [duplicate]函数不将右值引用作为参数? [复制]
【发布时间】:2020-09-11 10:52:14
【问题描述】:

我刚刚创建了一个将右值引用作为参数的函数,但是如果我传递 '67',它可以工作,但是假设“int&& ref = 67”,如果我将 ref 作为参数传递它会引发错误。

#include <iostream>
using namespace std;

void func(int&& a){
    std::cout << a << " from rvalue" << std::endl;
}


int main(){
    int&& ref = 6;
    //func(ref); // error
    func(6); // holds good
    return 0;
}

// error -> cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'

我不知道为什么它说左值是'int'类型,甚至参数是'int&&'类型(右值不是左值) 帮我看看有什么问题。 提前致谢......

【问题讨论】:

    标签: c++ rvalue-reference


    【解决方案1】:

    在本次通话中:

    //func(ref); // error
    

    reflvalue(因为它有名称)而不是右值引用。

    为了使其右值使用 move

      func(move(ref)); // this will cast ref to rvalue
    

    不要与 && 混淆(并非所有前面有 && 的东西都是右值):

    func(int&& x) 
    // && means here: you can call func() only with those expressions which can bind to rvalue (like numeric constants for ex.)
    // here you allow constructing x only from rvalues
    {
    BUT: (here it doesnt matter any more how x got constructed)
    ... for every usage of x within this scope: x is lvalue (because it has a name)
    

    【讨论】:

    • 好的。但是如果我用 func(int a); 重载这个函数呢?并将其调用为 func(std::move(ref));
    • 完全没问题,因为这两个都是有效的: int a = b;和int a = 6;对于常规类型(整数、浮点数等),a = move(b) 只会复制。 move() 仅在您的类型拥有某些资源的情况下才有意义,例如。字符串、向量等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多