Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::string::clear reclaim the memory associated with a string?

Tags:

c++

stl

For example, if loaded a text file into an std::string, did what I needed to do with it, then called clear() on it, would this release the memory that held the text? Or would I be better off just declaring it as a pointer, calling new when I need it, and deleting it when I'm done?

like image 592
chbaker0 Avatar asked Dec 08 '13 18:12

chbaker0


2 Answers

Calling std::string::clear() merely sets the size to zero. The capacity() won't change (nor will reserve()ing less memory than currently reserved change the capacity). If you want to reclaim the memory allocated for a string, you'll need to do something along the lines of

std::string(str).swap(str);

Copying the string str will generally only reserve a reasonable amount of memory and swapping it with str's representation will install the resulting representation into str. Obviously, if you want the string to be empty you could use

std::string().swap(str);
like image 68
Dietmar Kühl Avatar answered Sep 21 '22 05:09

Dietmar Kühl


The only valid method to release unused memory is to use member function shrink_to_fit(). Using swap has no any sense because the Standard does not say that unused memory will be released when this operation is used.

As an example

s.clear();
s.shrink_to_fit();
like image 43
Vlad from Moscow Avatar answered Sep 21 '22 05:09

Vlad from Moscow