首页 > 解决方案 > 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;
}

标签: c++c++11std

解决方案


推荐阅读