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

Requests the removal of unused capacity.

# Declarations

void shrink_to_fit();

(constexpr since C++20)

# Notes

In libstdc++, shrink_to_fit() is not available in C++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';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 755C++98std::string lacked explicit shrink-to-fit operationsprovided
LWG 2223C++981. references, pointers, and iterators were not invalidated2. there was no complexity requirement1. they may be invalidated2. required to be linear

# See also