我应该使用运算符+=而不是运算符+来连接std::string吗?

Should I use operator+= instead of operator+ for concatenating std::string?

本文关键字:运算符 std 连接 string 我应该      更新时间:2023-10-16

我经常看到这个结构有什么原因吗:

std::string myString = someString + "text" + otherString + "more text";

。取而代之的是这个(我很少看到):

std::string myString;
myString += someString += "text" += otherString += "more text";

阅读std::string API,在我看来,operator+创建了很多临时文件(也许通过编译器RVO进行了优化?),而operator+=变体仅附加文本。

在某些情况下,operator+变体将是要走的路。但是,当您只需要将文本附加到现有的非常量字符串时,为什么不直接使用 operator+= ?有什么理由不这样做吗?

-控制

operator+=具有错误的关联性,让您像第二个示例一样编写代码。为了做到这一点,你需要像这样用括号括起来:

(((myString += someString) += "text") += otherString) += "more text";
另一种为您提供

所需可读性和效率的方法是使用 std::stringstream

std::stringstream myString;
myString << someString << "text" << otherString << "more text";

std::string aaa += bbb;

类似于

std::string aaa = aaa + bbb;

所以在你的例子中将更改一些字符串和其他字符串。在通常情况下,使用 operator+ 时无需担心临时 - 在发布模式下,所有这些都将被消除(RVO 和/或其他优化)。

相关文章: