std::basic_string<CharT,Traits,Allocator>::reserve
來自 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 起) |
如果容量發生改變,所有迭代器和引用,包括末尾迭代器,都會失效。
目錄 |
[編輯] 引數
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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 847 | C++98 | 沒有異常安全保證 | 添加了強異常安全保證 |
[編輯] 參閱
返回當前分配儲存中可容納的字元數 (公開成員函式) | |
更改儲存的字元數 (公開成員函式) |