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

标签 c++ string gcc compiler-construction concatenation

我对 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 等同于 strcpy'ing a, ' ', b , 和 '\n' 进入足够大的内存块,还是使用和丢弃中间变量?

最佳答案

std::string c = a + ' ' + b + '\n'; 会做:

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+/

Concatenate strings Returns a newly constructed string object with its value being the concatenation of the characters in lhs followed by those of rhs.

启用优化后,编译器将/可能会删除这些不必要的拷贝

或者手动预分配字符串。

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 and its automatic memory resizing

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

关于c++ - GCC 如何连接多个 C++ std::string 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449891/

相关文章:

c++ - Q_GADGET 可以是其他 Q_GADGET 的属性吗?

Java 点不匹配 'any character'

mysql - 连接来自 2 个连续记录集的 2 个值 | MySQL

c - 无法以读取模式打开消息队列 (mq_open())

c++ - 空表达式的计算结果是否为 NOP?

c++ - C 中的 MPI 编程 - MPI_Send() 和 MPI_Recv() 地址问题

java - 正则表达式 : repeated concrete digit var vs repeated any digit var (Java)

c - 禁用 DejaGnu 选项

c++ - 为什么内置类型和类在不使用时会受到不同对待?

c++ - 如何从Visual C++中获取具体的windows服务可执行文件路径