I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Seems to be that the
ostr.str("")
call does the trick.You don't. Use two differently named streams for clarity and let the optimizing compiler figure out that it can reuse the old one.
I've used a sequence of clear and str in the past:
Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin:
That will prevent some reallocations done by
str
by overwriting whatever is in the output buffer currently instead. Results are like this:If you want to use the string for c-functions, you can use
std::ends
, putting a terminating null like this:std::ends
is a relict of the deprecatedstd::strstream
, which was able to write directly to a char array you allocated on the stack. You had to insert a terminating null manually. However,std::ends
is not deprecated, i think because it's still useful as in the above cases.If you're going to clear the buffer in a way that will cause it to be cleared before it's first use, you'll need to add something to the buffer first w/ MSVC.