C++ MemoryStream
January 17th, 2010When you have a file read into memory, and would like to use std::istream to access it, you have a couple of ways to do this. The obvious one is to create a std::stringstream from that memory location. It works fine, but it has a side effect of copying the data into its own buffer:
int main()
{
char text[] = "Some text string";
// this creates a copy of 'text' for std::stringstream
std::string data(text);
// this creates a reader that will use the copy of data
std::stringstream reader(data);
}
With large files this adds unnecessary overhead. So what is the “right” way to do this? I came up with something like that:
class membuf : public std::basic_streambuf<char>
{
public:
membuf(char* p, size_t n) {
setg(p, p, p + n);
}
}
int main()
{
char text[] = "Some text string";
// this creates a stream buffer at a given memory location
membuf buffer(text, sizeof(text));
// this creates an istream using the above buffer
std::istream reader(&mb);
}
Pretty simple and effective. And does not use anything but STL.








