gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:43:40 28 4
gpt4 key购买 nike

我对 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com