Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset string while keeping capacity

Tags:

c++

string

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.

like image 551
DaedalusAlpha Avatar asked Jan 21 '14 13:01

DaedalusAlpha


1 Answers

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

like image 53
user3159253 Avatar answered Oct 14 '22 18:10

user3159253