我应该使用运算符+=而不是运算符+来连接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;
所以在你的例子中将更改一些字符串和其他字符串。在通常情况下,使用 operator+ 时无需担心临时 - 在发布模式下,所有这些都将被消除(RVO 和/或其他优化)。
相关文章:
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 关于 std::min, std::max 中的比较运算符的混淆
- C++:无法使用 "=" 运算符更改 std::p air 的值
- 为 std::variant 提供一个运算符 ==
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- C++矩阵类运算符使用 std::common_type_t 和复数的实现
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 运算符/ STD :: Chrono ::持续时间和自定义类型与Clang
- ostream 和运算符 std::basic_string<char, std::char_traits<char>, std::分配器<char>>?
- 为什么显式运算符 std::string 不起作用
- 运算符< std::set 的重载
- 运算符< std::map 的 int 类型比较的重载?(我希望它按降序排序。
- 运算符=(std::p romise&&) 在 C++11 中的结果是什么?
- 绑定运算符=std::string的成员
- 传递 const std::auto_ptr<> 作为 std::auto_ptr<_Tp>::运算符 std::auto_ptr_ref<_Tp1>() 的参数丢
- 运算符<< std::stringstream 派生类的重载(只是)
- 重载运算符 std::ostream& 运算符<<打印实例内存地址