Namespaces
Variants

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

From cppreference.net
std::basic_string
void shrink_to_fit ( ) ;
(自 C++20 起为 constexpr)

请求移除未使用的容量。

这是一个非强制性的请求,用于将 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 输出(使用 -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++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 755 C++98 std::string 缺少显式收缩至合适大小的操作 已提供
LWG 2223 C++98 1. 引用、指针和迭代器未被置为无效
2. 没有复杂度要求
1. 它们可能被置为无效
2. 要求线性复杂度

参见

返回字符数量
(公开成员函数)
返回当前分配存储空间可容纳的字符数量
(公开成员函数)
修改存储的字符数量
(公开成员函数)