从没有复制的 char* 初始化 std::string [英] initializing std::string from char* without copy

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

问题描述

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

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

  1. 通过附加许多较小的 (C char*) 字符串来构建一个大字符串
  2. 修剪字符串
  3. 将字符串转换为 C++ const std::string 进行处理(只读)
  4. 重复

每次迭代的数据都是独立的.

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.

有没有一种方法可以将 C 字符串(char*)转换为 stl C++ 字符串(std::string)而不需要 std::string 在内部分配/复制数据?

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?

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

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

感谢您的回答,为清楚起见,我认为修改后的问题是:

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

如何有效地构建(通过多个附加)一个 stl C++ 字符串.如果在循环中执行此操作,其中每个循环完全独立,我该如何重新使用分配的空间.

推荐答案

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

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.

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

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