使用带有std :: string的&&运算符有什么用处

Blo*_*aRd 0 c++ rvalue-reference

我想在下面的例子中更好地理解运算符&&的使用 std::string

码:

#include <iostream>
using namespace std;

const std::string GetEditTxtAccount()
{
 std::string str = "Hello";
 return str;
}

int main()
{
   const string&& x = GetEditTxtAccount();
               ^^^
}
Run Code Online (Sandbox Code Playgroud)

那么为什么我们&&在主要使用运营商呢?

谢谢.

Lig*_*ica 7

此代码存储对新字符串的右值引用,依赖于生命周期扩展以保持实际字符串处于活动状态.

在这种情况下,它非常像做const string& x = GetEditTxtAccount(),这也毫无意义.

它也可以说是危险的,因为如果函数返回了一个引用,那么你可能会让它悬空.

当然,这样做没有任何好处.

只需声明一个正确的值:

const string x = GetEditTxtAccount();
Run Code Online (Sandbox Code Playgroud)

如果你担心副本,你就不会得到一个,因为移动语义(前C++ 17)和保证省略(因为C++ 17).

至于为什么作者以这种方式写它,好吧,有些人用rvalue refs超越顶部而没有真正理解为什么.