Namespaces
Variants

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

From cppreference.net
std::basic_string
void shrink_to_fit ( ) ;
(constexpr C++20부터)

사용되지 않는 용량의 제거를 요청합니다.

capacity() size() 로 축소하라는 비구속적 요청입니다. 이 요청이 이행되는지는 구현에 따라 다릅니다.

(그리고 오직) 재할당이 발생하는 경우에만, 모든 포인터, 참조자, 반복자는 무효화됩니다.

목차

복잡도

문자열의 크기에 선형적으로 비례합니다.

참고 사항

libstdc++에서, shrink_to_fit() 사용할 수 없습니다 C++98 모드에서.

예제

#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';
}

가능한 출력:

GCC 출력:
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 출력 (with -stdlib=libc++):
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

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 755 C++98 std::string 에 명시적 축소 맞춤(shrink-to-fit) 연산이 없었음 제공됨
LWG 2223 C++98 1. 참조, 포인터, 반복자가 무효화되지 않았음
2. 복잡도 요구사항이 없었음
1. 무효화될 수 있음
2. 선형 시간 복잡도 요구사항 추가

참고 항목

문자의 수를 반환합니다
(public member function)
현재 할당된 저장 공간에 보관할 수 있는 문자의 수를 반환합니다
(public member function)
저장된 문자의 수를 변경합니다
(public member function)