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

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

为什么我经常看到这个结构:

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;

因此在您的示例中将更改 someStringotherString。 在通常情况下,当使用 operator+ 时,您不需要担心临时对象 - 在发布模式下,所有这些都将被消除(RVO and/or 其他优化)。