gpt4 book ai didi

c++ - 为什么不能在函数之间直接传递右值引用参数?

转载 作者:行者123 更新时间:2023-12-03 06:51:45 25 4
gpt4 key购买 nike

我的代码如下:

#include <iostream>
using namespace std;

class A{
public:
void sendByRvalue(string&& str){
cout << str << endl;
}
};

class B{
private:
A a;
void send(string&& str){
a.sendByRvalue(str);
}
public:
void run(const string& str){
send("run " + str + "\n");
}
};

int main(void){
string str("hello world");
B b;
b.run(str);
return 0;
}
当我编译上面显示的代码时,出现了一些编译错误:
enter image description here
看来 strB::send函数已更改为左值。然后我换了 B::send的工具, 喜欢:
class B{
private:
A a;
void send(string&& str){
cout << boolalpha << is_rvalue_reference<decltype(str)>::value << endl;
a.sendByRvalue(std::move(str));
}
public:
void run(const string& str){
send("run " + str + "\n");
}
};
一切都很顺利,但是这个程序的输出让我更加困惑。输出如下:
enter image description here
为什么参数 str 是右值引用,但我无法将其传递给函数 A::sendByRvalue直接没有 std::move ?

最佳答案

str是一个命名的右值引用,在语言中被视为左值。右值只是 xvalues 或 prvalues,和 str都不是。
来自 the standard 的注释, 关于 xvalue 规则:

In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not.


struct A {
int m;
};
A&& operator+(A, A);
A&& f();

A a;
A&& ar = static_cast<A&&>(a);

The expressions f(), f().m, static_­cast<A&&>(a), and a + a are xvalues. The expression ar is an lvalue.

关于c++ - 为什么不能在函数之间直接传递右值引用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64798137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com