C :RVALUE参考转换为非const lvalue-Reference

C++: rvalue reference converted to non-const lvalue-reference

本文关键字:const lvalue-Reference 转换 RVALUE 参考      更新时间:2023-10-16

我已经阅读了此内容,但是我仍然不明白为什么以下代码在xcode中编译:

void func2(string &s) {
    s = "yyyyy";
}
void func(string &&s) {
    func2(s);
}
int main() {
    func("xxxxx");
    return 0;
}

我认为不应该将rvalue参考转换为非const lvalue参考,对吗?通常,LVALUE参考文献和RVALUE参考文献之间的转换规则是什么?我已经知道const lvalue参考可以与rvalues结合,但是rvalue参考(而不是rvalues)呢?非常感谢!

r值引用是对原始对象的引用,因此将其转换为l值参考将仅引用原始对象。
一旦将移动构造函数调用后,原始对象应重置为原点状态,对其进行任何引用。

此示例可能会澄清它:

#include <iostream>
using namespace std;
int main()
{
    string s = "my string";
    string &&rval = move(s);
    cout << '"' << rval << '"' << endl; // "my string"
    cout << '"' << rval << '"' << endl; // "my string"
    cout << '"' << s << '"' << endl;    // "my string"
    string &lval = rval;
    cout << '"' << lval << '"' << endl; // "my string"
    string s2(move(rval));
    cout << '"' << rval << '"' << endl; // ""
    cout << '"' << lval << '"' << endl; // ""
    cout << '"' << s << '"' << endl;    // ""
    cout << '"' << s2 << '"' << endl;   // "my string"
    return 0;
}