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

出自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
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 << "std::string 的大小是 " << sizeof s << " 个字节\n"
        << "默认构造后的容量是 " << s.capacity() 
        << ",大小是 " << s.size() << '\n';
 
    for (int i = 0; i < 42; i++)
        s.append(" 42 ");
    std::cout << "后附 42 次后的容量是 " << s.capacity() 
        << ",大小是 " << s.size() << '\n';
 
    s.clear();
    std::cout << "clear() 后的容量是 " << s.capacity() 
        << ",大小是 " << s.size() << '\n';
 
    s.shrink_to_fit();
    std::cout << "shrink_to_fit() 后的容量是 " << s.capacity() 
        << ",大小是 " << s.size() << '\n';
}

可能的輸出:

GCC 输出:
std::string 的大小是 32 个字节
默认构造后的容量是 15,大小是 0
后附 42 次后的容量是 240,大小是 168
clear() 后的容量是 240,大小是 0
shrink_to_fit() 后的容量是 15,大小是 0
 
clang 输出(-stdlib=libc++):
std::string 的大小是 24 个字节
默认构造后的容量是 22,大小是 0
后附 42 次后的容量是 191,大小是 168
clear() 后的容量是 191,大小是 0
shrink_to_fit() 后的容量是 22,大小是 0

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 出版時的行為 正確行為
LWG 755 C++98 std::string 缺少顯式的移除未使用的容量的操作 已提供
LWG 2223 C++98 1. 引用、指針和迭代器不會失效
2. 沒有複雜度要求
1. 可能會失效
2. 要求為線性

[編輯] 參閱

返回字元數
(公開成員函數) [編輯]
返回當前對象分配的存儲空間能保存的字元數量
(公開成員函數) [編輯]
更改存儲的字元數
(公開成員函數) [編輯]