初始化std :: string从char *无副本 [英] initializing std::string from char* without copy

查看:144
本文介绍了初始化std :: string从char *无副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一种情况,我需要处理大量(许多GB)的数据量:



  1. 将字符串转换为C ++ const std :: string进行处理(只读) )

  2. 重复

每次迭代中的数据是独立的。

$ b我的问题是,我想尽量减少(如果可能消除)堆分配的内存使用,因为它是我最大的性能问题。



有没有办法将C字符串(char *)转换成stl C ++字符串(std :: string),而不需要std :: string来内部分配/复制数据?



或者,我可以使用stringstreams或类似的东西重新使用大型缓冲区吗?



对于答案,为了清楚,我认为一个修订的问题是:



如何高效地构建一个stl C ++字符串(通过多个附加)。如果在一个循环中执行此操作,每个循环都是完全独立的,那么如何重新使用这个分配的空间。


解决方案

在步骤1中是否可以使用C ++字符串?如果你使用 string :: reserve(size_t),你可以分配足够大的缓冲区来防止多个堆分配,同时附加较小的字符串,然后你可以使用



请参阅此链接了解有关保留功能的更多信息。


I have a situation where I need to process large (many GB's) amounts of data as such:

  1. build a large string by appending many smaller (C char*) strings
  2. trim the string
  3. convert the string into a C++ const std::string for processing (read only)
  4. repeat

The data in each iteration are independent.

My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.

Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?

Alternatively, could I use stringstreams or something similar to re-use a large buffer?

Edit: Thanks for the answers, for clarity, I think a revised question would be:

How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.

解决方案

Is it at all possible to use a C++ string in step 1? If you use string::reserve(size_t), you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps.

See this link for more information on the reserve function.

这篇关于初始化std :: string从char *无副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆