std::basic_string<CharT,Traits,Allocator>::shrink_to_fit (3) - Linux Man Pages

std::basic_string<CharT,Traits,Allocator>::shrink_to_fit: std::basic_string<CharT,Traits,Allocator>::shrink_to_fit


std::basic_string<CharT,Traits,Allocator>::shrink_to_fit - std::basic_string<CharT,Traits,Allocator>::shrink_to_fit


void shrink_to_fit(); (since C++11)

Requests the removal of unused capacity.
It is a non-binding request to reduce capacity() to size(). It depends on the implementation if the request is fulfilled.
If (and only if) reallocation takes place, all pointers, references, and iterators are invalidated.



Return value



(unspecified) (until C++17)
Linear in the size of the string (since C++17)


// Run this code

  #include <iostream>
  #include <string>

  int main()
      std::string s;
      std::cout << "Default-constructed capacity is " << s.capacity() << '\n';
      std::cout << "Capacity of a 100-element string is " << s.capacity() << '\n';
      std::cout << "Capacity after clear() is " << s.capacity() << '\n';
      std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << '\n';

Possible output:

  Default-constructed capacity is 0
  Capacity of a 100-element string is 100
  Capacity after clear() is 100
  Capacity after shrink_to_fit() is 0

See also

         returns the number of characters
size (public member function)
         returns the number of characters that can be held in currently allocated storage
capacity (public member function)