名稱空間
變體
操作

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++ 中,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. 要求為線性複雜度

[編輯] 另請參閱

返回字元數
(公共成員函式) [編輯]
返回當前分配儲存中可容納的字元數
(公共成員函式) [編輯]
更改儲存的字元數
(公共成員函式) [編輯]