名前空間
変種
操作

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

From 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++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 755 C++98 std::stringに明示的なshrink-to-fit操作が欠けていた 提供された
LWG 2223 C++98 1. 参照、ポインタ、イテレータは無効化されていなかった
2. 計算量要件がなかった
1. 無効化される可能性がある
2. 線形であることが要求される

[編集] 関連項目

文字数を返す
(public member function) [編集]
現在割り当てられているストレージに保持できる文字数を返す
(public member function) [編集]
格納されている文字数を変更する
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)