Wednesday, December 27, 2017

C++11: std::basic_string::shrink_to_fit()

C++11 added the string function shrink_to_fit() to suggest to the system to reduce the capacity to size. Here is an example:

#include <iostream>
#include <string>

int main()
{
  std::string myString;

  std::cout << myString.capacity() << " "; // 15

  myString.resize(1000);
  std::cout << myString.capacity() << " "; // 1007

  myString.clear();
  myString.shrink_to_fit();
  std::cout << myString.capacity() << " "; // 15

  std::cout << std::endl;
  return 0;
}
// Output: 15 1007 15
Reference: http://en.cppreference.com/w/cpp/string/basic_string/shrink_to_fit

No comments:

Post a Comment