命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
void shrink_to_fit();
(constexpr since 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 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=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. 要求为线性

[编辑] 参见

返回字符数
(公共成员函数) [编辑]
返回当前已分配存储中可以容纳的字符数
(公共成员函数) [编辑]
更改存储的字符数
(公共成员函数) [编辑]