使用大长度缓冲区初始化stringstream是否会使内存使用量翻倍

时间:2017-03-31 16:25:21

标签: c++ buffer sstream

假设我有一个长度为100MB char[100*1024*1024]的缓冲区。我想在这个缓冲区上使用stringstream工具,就像格式化读取一样,所以我使用这个数组定义了一个新的stringstream ss(arr)。所以我想知道我的程序在运行时是否总共使用了200MB?我正在研究大数据和内存使用是至关重要的。实际上我定义了一个char缓冲区并用这个缓冲区初始化我的自定义istream并解决了我的内存问题。但我仍然感到困惑,不管我的第二种方式是否多余。

1 个答案:

答案 0 :(得分:1)

  

所以我想知道我的程序在运行时是否总共使用了200MB   不是吗?

如果从char数组构造stringstream,它将至少加倍内存使用量。来自std::basic_stringstream constructor的参考:

  

使用str的副本作为基础字符串的初始内容   设备

您可以编写自己的流缓冲区来创建非拥有的字符串流,但boost::iostreams库已经通过array devices提供了该字符串流。

namespace io = boost::iostreams;

char str[100*1024*1024];

// No copy of str is made here! The stream just stores pointer and size of array.
io::stream<io::array_source> strm( str, sizeof(str) );

// Do something with the stream as usual. It is fully compatible with standard streams.
int x;
strm >> x;

有一个很好的在线编译器,可以显示峰值内存使用情况。 在以下示例中,我将从10 MiB阵列创建流。

Live example using std::stringstream。峰值为31(!)MiB。

Live example using boost::array_source。峰值仅为11 MiB。

使用std::stringstream时,为什么char数组大小的内存使用率甚至 3x ?因为我们必须首先从char数组创建一个临时string,因为std::stringstream没有一个带有char指针的构造函数。