Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make std::string use less memory?

Before I begin, I need to state that my application uses lots of strings, which are on average quite small, and which do not change once created.

In Visual Studio 2010, I noticed that the capacity of std::string is at least 30. Even if I write std::string str = "test";, the capacity of str is 30. The function str.shrink_to_fit() does nothing about this although a function with the same name exists for std::vector and works as expected, namely decreasing the capacity so that capacity == size.

  1. Why does std::string::shrink_to_fit() not work at expected?
  2. How can I ensure that the string allocates the least amount of memory?
like image 839
Fabian Avatar asked Jan 06 '16 13:01

Fabian


1 Answers

  1. Your std::string implementation most likely uses some form of the short string optimization resulting in a fixed size for smaller strings and no effect for shrink_to_fit. Note that shrink_to_fit is non-binding for the implementation, so this is actually conforming.
  2. You could use a vector<char> to get more precise memory management, but would loose some of the additional functionality of std::string. You could also write your own string wrapper which uses a vector internally.
like image 110
pmr Avatar answered Sep 22 '22 15:09

pmr