C++ 参考手册

位置:首页 > C++ 参考手册 >字符串库 >std::basic_string > std::basic_string<CharT,Traits,Allocator>::shrink_to_fit

void shrink_to_fit();
(C++11 起)
(C++20 前)
constexpr void shrink_to_fit();
(C++20 起)

请求移除未使用的容量。

这是减少 capacity()size() 的非强制请求。是否满足请求取依赖于实现。

若(且唯若)发生重分配,则非法化所有指针、引用和迭代器。

参数

(无)

返回值

(无)

复杂度

(未指明)

(C++17 前)

与 string 大小成线性

(C++17 起)

示例

#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::cout << "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 a couple of 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';
}

可能的输出:

Default-constructed capacity is 15 and size 0
Capacity after a couple of appends is 240 and size 168
Capacity after clear() is 240 and size 0
Capacity after shrink_to_fit() is 15 and size 0

参阅

返回字符数
(公开成员函数)
返回当前对象分配的存储空间能保存的字符数量
(公开成员函数)