std::basic_string<CharT,Traits,Allocator>::reserve
From cppreference.com
< cpp | string | basic string
| (1) | ||
void reserve( size_type new_cap = 0 ); |
(C++20まで) | |
| constexpr void reserve( size_type new_cap ); |
(C++20以降) | |
| void reserve(); |
(2) | (C++20以降) (C++20で非推奨) (C++26で削除) |
1) std::basic_string オブジェクトに、計画されたサイズの変更を通知し、ストレージ割り当てを適切に管理できるようにします。
- new_cap が現在の capacity() より大きい場合、新しいストレージが割り当てられ、capacity() は new_cap 以上になります。
|
(C++20まで) |
|
(C++20以降) |
容量の変更が発生した場合、past-the-end イテレータを含むすべてのイテレータと参照は無効になります。
目次 |
[編集] パラメータ
| new_cap | - | 文字列の新しい容量 |
[編集] 戻り値
(なし)
[編集] 例外
new_cap が max_size() より大きい場合、std::length_error をスローします。
std::allocator_traits<Allocator>::allocate() によってスローされる可能性のあるすべての例外(例: std::bad_alloc)をスローする可能性があります。
何らかの理由で例外がスローされた場合、この関数は効果がありません(強力な例外安全保証)。
[編集] 計算量
文字列の size() に対して最大線形。
[編集] 例
このコードを実行
#include <cassert> #include <iostream> #include <string> int main() { std::string s; std::cout << "1) Initially: " << s.capacity() << '\n'; const std::string::size_type new_cap{101u}; s.reserve(new_cap); assert(s.capacity() >= new_cap); std::cout << "2) After reserve(" << new_cap << "): " << s.capacity() << '\n'; // observing the capacity growth factor auto cap{s.capacity()}; for (int check{}; check != 4; ++check) { while (cap == s.capacity()) s += '$'; cap = s.capacity(); std::cout << (3) + check << ") Capacity: " << cap << '\n'; } // s.reserve(); // deprecated/removed in C++20/26, use: s.shrink_to_fit(); std::cout << "7) After shrink_to_fit: " << s.capacity() << '\n'; }
実行結果の例
1) Initially: 15 2) After reserve(101): 101 3) Capacity: 202 4) Capacity: 404 5) Capacity: 808 6) Capacity: 1616 7) After shrink_to_fit: 809
[編集] 欠陥報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 847 | C++98 | 例外安全性保証がなかった | 強力な例外安全性保証を追加 |
[編集] 関連項目
| 現在割り当てられているストレージに保持できる文字数を返す (public member function) | |
| 格納されている文字数を変更する (public member function) |