【问题标题】:How to pass rvalue reference from caller to callee如何将右值引用从调用者传递给被调用者
【发布时间】:2019-03-03 01:09:07
【问题描述】:

假设我在下面有代码

#include <iostream>

void foo(std::string && s) { std::cout << s; }

void bar(std::string && s) { foo(s); }

int main() {

  bar("abc");

  return 0;
}

我收到编译错误:

错误:无法绑定‘std::string {aka std::basic_string}’左值 到‘std::string&& {aka std::basic_string&&}’ 无效 bar(std::string && s) { foo(s); }

【问题讨论】:

    标签: c++11 rvalue-reference


    【解决方案1】:

    使用来自&lt;utility&gt;std::move

    #include <iostream>
    #include <utility>
    
    void foo(std::string && s) { std::cout << s; }
    
    void bar(std::string && s) { foo(std::move(s)); }
    
    int main() {
    
      bar("abc");
    
      return 0;
    }
    

    std::moveactually just a little bit of syntactical sugar,但它是转发右值引用的常用方式。

    【讨论】:

    • 那么为什么我需要在这里使用 std::move 呢?我得到的参数是&&,我把它给了&&。那是因为我不能将 && 分配给 && 吗?当我使用 std::move 时,实际上发生的事情不是 && 分配给 &&,而只是一个动作?
    • 指定一个命名参数传递一个左值。对于foo(s),传递的参数是一个左值引用。左值引用不能转换为右值引用。 std::move() 基本上是将左值引用转换为右值引用的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 2014-11-26
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多