std::basic_string<CharT,Traits,Allocator>:: shrink_to_fit
From cppreference.net
<
cpp
|
string
|
basic string
C++
Strings library
| Classes | ||||
|
(C++17)
|
||||
std::basic_string
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
void
shrink_to_fit
(
)
;
|
(constexpr C++20以降) | |
未使用の容量の削除を要求します。
これは 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++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 755 | C++98 |
std::string
には明示的な縮小フィット操作が欠如していた
|
提供された |
| LWG 2223 | C++98 |
1. 参照、ポインタ、イテレータは無効化されなかった
2. 計算量の要件がなかった |
1. 無効化される可能性がある
2. 線形であることが要求される |
関連項目
|
文字数を返す
(public member function) |
|
|
現在割り当てられているストレージに格納可能な文字数を返す
(public member function) |
|
|
格納されている文字数を変更する
(public member function) |