LVALUE参考可以与RVALUE参考结合,但不能与STD :: MOVE的结果结合。

发布于 2025-02-06 16:24:38 字数 600 浏览 2 评论 0原文

我的功能具有lvalue参考作为参数,我发现我也可以通过 对此的rvalue引用。但是,当我将std :: Move的结果传递给功能时,我会收到一个错误,告诉我我不能将非const lvalue引用绑定到rvalue。

#include <iostream>
#include <string>

template<typename T>
void foo(T& a) { }

struct A {
    std::string s;
};

int main(int argc,char** argv) {
    A a{"a"};
    A&& ra = std::move(a); 
    foo(ra);            // OK
    foo(std::move(a));  // Error
    return 0;
}

我当时认为std ::移动还返回rvalue参考。 使用中间RVALUE参考作为参数和直接使用std :: Move作为参数的结果有什么区别?

I have a function that has a lvalue reference as argument, and I found that I can also pass
a rvalue reference to it. However, when I passing the result of std::move to the function, I get an error which tells me that I cannot bind non-const lvalue reference to an rvalue.

#include <iostream>
#include <string>

template<typename T>
void foo(T& a) { }

struct A {
    std::string s;
};

int main(int argc,char** argv) {
    A a{"a"};
    A&& ra = std::move(a); 
    foo(ra);            // OK
    foo(std::move(a));  // Error
    return 0;
}

I was thinking that std::move also returns a rvalue reference.
What is the difference between using an intermediate rvalue reference as argument and directly using the result of std::move as argument?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凝望流年 2025-02-13 16:24:38

RA是一个命名变量。因此,它是一个LVALUE,可以与LVALUE参考结合。

std ::移动(a)返回a&amp;&amp;,但是返回的值是一个prvalue。 LVALUE参考不能与Prvalues结合。

ra is a named variable. As such, it is an lvalue and can be bound to an lvalue reference.

std::move(a) returns a A&&, but that returned value is a prvalue. lvalue references cannot bind to prvalues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文