std::string 中的 && 运算符有什么用
what is the use of the && operator with std::string
我想更好地理解下面示例中运算符 && 与 std::string
的用法
代码:
#include <iostream>
using namespace std;
const std::string GetEditTxtAccount()
{
std::string str = "Hello";
return str;
}
int main()
{
const string&& x = GetEditTxtAccount();
^^^
}
那么我们为什么要在 main 中使用运算符 &&
?
谢谢。
此代码正在存储对新字符串的右值引用,依靠生命周期延长来保持实际字符串的存活。
在这种情况下,这很像 const string& x = GetEditTxtAccount()
,这也是毫无意义的。
这也可以说是危险的,因为如果函数返回一个引用,那么你可能会让它悬空。
当然这样做没有任何好处。
只需声明一个适当的值即可:
const string x = GetEditTxtAccount();
如果你担心副本,你不会得到副本,因为移动语义(pre-C++17)和保证省略(自 C++17 起)。
至于为什么作者是这样写的,好吧,有些人在没有真正理解为什么的情况下就使用右值引用。
我想更好地理解下面示例中运算符 && 与 std::string
代码:
#include <iostream>
using namespace std;
const std::string GetEditTxtAccount()
{
std::string str = "Hello";
return str;
}
int main()
{
const string&& x = GetEditTxtAccount();
^^^
}
那么我们为什么要在 main 中使用运算符 &&
?
谢谢。
此代码正在存储对新字符串的右值引用,依靠生命周期延长来保持实际字符串的存活。
在这种情况下,这很像 const string& x = GetEditTxtAccount()
,这也是毫无意义的。
这也可以说是危险的,因为如果函数返回一个引用,那么你可能会让它悬空。
当然这样做没有任何好处。
只需声明一个适当的值即可:
const string x = GetEditTxtAccount();
如果你担心副本,你不会得到副本,因为移动语义(pre-C++17)和保证省略(自 C++17 起)。
至于为什么作者是这样写的,好吧,有些人在没有真正理解为什么的情况下就使用右值引用。