std::basic_string<CharT,Traits,Allocator>::shrink_to_fit
来自 zh.cppreference.net
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. 要求线性复杂度 |
参见
|
返回字符数量
(公开成员函数) |
|
|
返回当前分配存储空间可容纳的字符数量
(公开成员函数) |
|
|
修改存储的字符数量
(公开成员函数) |