std::basic_string<CharT,Traits,Allocator>::shrink_to_fit
来自 cppreference.com
< cpp | string | basic string
void shrink_to_fit(); |
(从 C++20 开始为 constexpr) | |
请求移除未使用的容量。
这是一个非强制性请求,用于将 capacity() 减少到 size()。是否满足该请求取决于实现。
如果(且仅当)发生重新分配,所有指针、引用和迭代器将失效。
内容 |
[编辑] 参数
(无)
[编辑] 返回值
(无)
[编辑] 复杂度
(未指定) |
(直到 C++17) |
字符串大小的线性复杂度。 |
(从 C++17 开始) |
[编辑] 说明
在 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 缺少显式的收缩到适合的操作 |
提供 |
[编辑] 参见
返回字符数量 (公共成员函数) | |
返回当前分配的存储空间中可以容纳的字符数量 (公共成员函数) | |
更改存储的字符数量 (公共成员函数) |