GCC如何连接多个c++ std::string变量
How are mulitple C++ std::string variables concatenated by GCC?
我对GCC中std::string
连接的内部实现很感兴趣。具体来说,假设我想连接一些相对较大的字符串,a
和b
。一般来说,我对字符串连接非常谨慎,而字符串在许多高级语言中是不可变的。
#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
将a
, ' '
, 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
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 可组合的lambda/std::函数与std::可选