c++ - C++ std::string + 运算符与追加
问题描述
我看到了如下代码。我的理解是它有以下性能问题:
应该使用 string.append 而不是 + 运算符。str1 + "abc" 将导致一个新的字符串对象,其底层堆数据从 str1 复制并从 "abc" 移动(因为它匹配字符串运算符 + (string& lhs, string&& rhs)(。然后在表达式中加上额外的 "+" , 它将创建新的字符串对象总共 3 次, 多个重叠的复制操作是浪费的. string.append 应该做就地扩展. 它既不会导致创建 3 个字符串对象, 也不会导致浪费复制. 有人可以确认我的理解?
class Foo {
public:
std::string GetCombined() {
return str1 + "abc" + str2 + "xyz";
}
private:
std::string str1, str2;
}
解决方案
推荐阅读
- python - 连接列表中 2 个字符串中的每个字符
- angular - Angular7 + RxJs 多个订阅者到同一个 Observable
- architecture - 每个客户的分布式作业队列
- django - Django 2.1 如何使用自定义函数显示上下文
- mysql - 同一行 MySQL 中的两个行字段之间交换数据
- python - 如何使用 numpy 矩阵有条件地做某事
- amazon-web-services - 运行代码部署挂钩时找不到 Go 命令
- django - Django:使用 POST 的选项值时不会出现消息错误
- angular - 没有先前路线时的转移表达式
- shell - 使用 SED 交换一行中出现的多个单词和数字