public member function
<string>

std::basic_string::shrink_to_fit

void shrink_to_fit();
Shrink to fit
Requests the basic_string to reduce its capacity to fit its size.

The request is non-binding, and the container implementation is free to optimize otherwise and leave the basic_string with a capacity greater than its size.

This function has no effect on the string length and cannot alter its content.

Parameters

none

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// string::shrink_to_fit
#include <iostream>
#include <string>

int main ()
{
  std::string str (100,'x');
  std::cout << "1. capacity of str: " << str.capacity() << '\n';

  str.resize(10);
  std::cout << "2. capacity of str: " << str.capacity() << '\n';

  str.shrink_to_fit();
  std::cout << "3. capacity of str: " << str.capacity() << '\n';

  return 0;
}


Possible output:
1. capacity of str: 100
2. capacity of str: 100
3. capacity of str: 10

Complexity

Unspecified, but generally constant.

Iterator validity

Any iterators, pointers and references related to this object may be invalidated.

Data races

The object is modified.

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the basic_string.

If the type uses the default allocator, a bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also