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

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
basic_string::shrink_to_fit
(DR*)
Modifiers
Search
Operations
(哋它亢++23)
Constants
Non-member functions
I/O
Comparison
(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(哋它亢++20)
Numeric conversions
(哋它亢++11)(哋它亢++11)(哋它亢++11)
(哋它亢++11)(哋它亢++11)
(哋它亢++11)(哋它亢++11)(哋它亢++11)
(哋它亢++11)
(哋它亢++11)
Literals
(哋它亢++14)
Helper classes
Deduction guides (哋它亢++17)

 
void shrink_to_fit();
(constexpr since 哋它亢++20)

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.

Parameters

(none)

Return value

(none)

Complexity

(unspecified)

(until 哋它亢++17)

Linear in the size of the string.

(since 哋它亢++17)

Notes

In libstd哋它亢++, shrink_to_fit() is not available in 哋它亢++98 mode.

Example

#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::cout << "Size of std::string is " << sizeof s << " bytes\n"
        << "Default-constructed capacity is " << s.capacity() 
        << " and size is " << s.size() << '\n';
 
    for (int i = 0; i < 42; i++)
        s.append(" 42 ");
    std::cout << "Capacity after 42 appends is " << s.capacity() 
        << " and size is " << s.size() << '\n';
 
    s.clear();
    std::cout << "Capacity after clear() is " << s.capacity() 
        << " and size is " << s.size() << '\n';
 
    s.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << s.capacity() 
        << " and size is " << s.size() << '\n';
}

Possible output:

GCC output:
Size of std::string is 32 bytes
Default-constructed capacity is 15 and size 0
Capacity after 42 appends is 240 and size 168
Capacity after clear() is 240 and size 0
Capacity after shrink_to_fit() is 15 and size 0
 
clang output (with -stdlib=lib哋它亢++):
Size of std::string is 24 bytes
Default-constructed capacity is 22 and size is 0
Capacity after 42 appends is 191 and size is 168
Capacity after clear() is 191 and size is 0
Capacity after shrink_to_fit() is 22 and size is 0

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published 哋它亢++ standards.

DR Applied to Behavior as published Correct behavior
LWG 755 哋它亢++98 std::string lacked explicit shrink-to-fit operations provided

See also

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