GCC如何连接多个c++ std::string变量

How are mulitple C++ std::string variables concatenated by GCC?

本文关键字:c++ std string 变量 何连接 连接 GCC      更新时间:2023-10-16

我对GCC中std::string连接的内部实现很感兴趣。具体来说,假设我想连接一些相对较大的字符串,ab。一般来说,我对字符串连接非常谨慎,而字符串在许多高级语言中是不可变的。

#include <iostream>
int main(){
  std::string a = "This would be some kind of data.";
  std::string b = "To be concatenated with this, and other things.";
  // Is building c this way equivalent to strcpy'ing a, ' ', b, and 'n' into
  // a sufficiently large chunk of memory, or are intermediate variables used
  // and discarded?
  std::string c = a + ' ' + b + 'n';
  std::cout << c;
}

以这种方式构建c是否等同于strcpya, ' ', b'n'放入足够大的内存块中,或者使用中间变量并丢弃?

std::string c = a + ' ' + b + 'n'; will do:

std::string tmp1 = a.operator+('');
std::string tmp2 = tmp1.operator+(b);
std::string c = tmp2.operator+('n');
http://www.cplusplus.com/reference/string/string/operator +/

concatate strings返回一个新构造的字符串对象值是LHS中字符的连接,后面跟着

通过启用优化,编译器将/可能会删除这些不必要的副本

或者手动预分配字符串。

std::string c;
c.reserve(a.size()+1+b.size()+1);
c += a;
c += ' ';
c += b;
c += 'n';

现在它不会创建临时对象了。即使没有reserve。它不会经常重新分配(在大字符串上)。因为缓冲区增长new_size=2*size(在libstdc++中)

参见std::string及其自动内存大小调整

还值得一提的是c++ 11可以std::move内存,参见https://stackoverflow.com/a/9620055/362904