std::basic_string<CharT,Traits,Allocator>::shrink_to_fit
来自 cppreference.cn
< cpp | string | basic_string
void shrink_to_fit(); |
(C++20 起为 constexpr) | |
请求移除未使用的容量。
这是一个非绑定请求,用于将 capacity() 减少到 size()。该请求是否被实现取决于具体实现。
如果(且仅当)发生重新分配时,所有指针、引用和迭代器都将失效。
目录 |
[编辑] 复杂度
与字符串大小呈线性关系。
[编辑] 注意
在 libstdc++ 中,C++98 模式下不可用 shrink_to_fit()
。
[编辑] 示例
运行此代码
#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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 755 | C++98 | std::string 缺少显式的 shrink-to-fit 操作 |
已提供 |
LWG 2223 | C++98 | 1. 引用、指针和迭代器未失效 2. 没有复杂度要求 |
1. 它们可能失效 2. 要求为线性复杂度 |
[编辑] 另请参阅
返回字符数 (公共成员函数) | |
返回当前分配存储中可容纳的字符数 (公共成员函数) | |
更改存储的字符数 (公共成员函数) |