Writing std::ostringstream to file without copying?
Given a function that takes an output strin开发者_开发百科gstream as an argument:
void Foo(const std::ostringstream& _oss);
Is there any way of writing the stream buffer to a file WITHOUT having to call str() ?
I want to avoid copying the buffer (which str() does).
void Foo(const std::ostringstream& _oss);
{
std::ofstream f("foo.bin");
//WANT: write _oss to f without copying the buffer?
}
There's an operator<<()
taking a stream buffer:
f << _oss.rdbuf();
However, the buffer needs to be really big for this to make a noticeable difference. Usually, writing to disk will dominate the time needed for this anyway.
Note that I'd avoid creating identifiers with leading underscores.
You can't write it to file without copying- because that's what writing to a file does, it copies it out of memory and on to the disk.
Of course, if you want to get technical about this, you could utilize a memory mapped file.
精彩评论