7

I've read a lot of questions here on SO about how to clear a string entirely (i.e. resetting the capacity, freeing memory). My question though is the exact opposite; is there any reliable way of resetting a string (the length) while being guaranteed that its capacity is kept intact?

Example: reusing a temporary string in a loop.

Likely this will happen by default if I do something like

str.clear()
str.reserve(256)

in each loop iteration, at least when using Visual Studio according to the answer to this post: Specific behaviour of std::string on visual studio?

But relying on "likely" seems a bit risky.

Community
  • 1
  • 1
DaedalusAlpha
  • 1,610
  • 4
  • 20
  • 33

1 Answers1

10

According to http://en.cppreference.com/w/cpp/string/basic_string/clear clear() doesn't free internal buffer and keeps capacity intact.

user3159253
  • 16,836
  • 3
  • 30
  • 56
  • Hah, so it says. Guess I don't even have to call str.reserve(256) then, it will be kept anyway. I should check out the documentation better before posting here... – DaedalusAlpha Jan 21 '14 at 13:48