简体   繁体   English

&&运算符与std :: string的用法是什么

[英]what is the use of the && operator with std::string

I would like to better understand the use of the operator && in the example below with std::string 我想更好地理解下面示例中std::string运算符&&的使用

Code: 码:

#include <iostream>
using namespace std;

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

int main()
{
   const string&& x = GetEditTxtAccount();
               ^^^
}

so why did we used the operator && in the main? 那么为什么我们在主体中使用运算符&&

Thank you. 谢谢。

This code is storing an rvalue reference to the new string, relying on lifetime extension to keep the actual string alive. 这段代码存储了对新字符串的右值引用,它依赖生命周期延长来使实际字符串保持活动状态。

In this case it's pretty much like doing const string& x = GetEditTxtAccount() , which is also pointless. 在这种情况下,这很像执行const string& x = GetEditTxtAccount() ,这也是毫无意义的。

It's also arguably dangerous because if the function returned a reference then you'd potentially have it dangling. 这也可以说是很危险的,因为如果函数返回了引用,则可能会使它悬空。

Certainly there is no benefit in doing this. 当然这样做没有任何好处。

Just declare a proper value instead: 只需声明一个适当的值即可:

const string x = GetEditTxtAccount();

If you're worried about copies, you won't get one, because of move semantics (pre-C++17) and because of guaranteed elision (since C++17). 如果您担心副本,由于移动语义(C ++ 17之前的版本)和有保证的省略号(自C ++ 17起),您将一无所获。

As for why the author wrote it this way, well, some people go over the top with rvalue refs without really understanding why. 至于作者为什么这样写,好吧,有些人在没有真正理解原因的情况下就使用了右值引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM