(1) | ||
void reserve( size_type new_cap = 0 ); | (until C++20) | |
constexpr void reserve( size_type new_cap ); | (since C++20) | |
void reserve(); | (2) | (since C++20) (deprecated) |
std::basic_string
object of a planned change in size, so that it can manage the storage allocation appropriately. new_cap
is greater than the current capacity()
, new storage is allocated, and capacity()
is made equal or greater than new_cap
.
| (until C++20) |
| (since C++20) |
capacity()
has an unspecified value greater than or equal to size()
.new_cap | - | new capacity of the string |
(none).
Throws std::length_error
if new_cap
is greater than max_size()
.
May throw any exceptions thrown by std::allocator_traits<Allocator>::allocate()
, such as std::bad_alloc
.
If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee).
At most linear in the size()
of the string.
#include <cassert> #include <iostream> #include <string> int main() { std::string s; const std::string::size_type new_capacity{100u}; std::cout << "Before: " << s.capacity() << '\n'; s.reserve(new_capacity); std::cout << "After: " << s.capacity() << '\n'; assert(new_capacity <= s.capacity()); // 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 << "New capacity: " << cap << '\n'; } // s.reserve(); // deprecated in C++20, use: s.shrink_to_fit(); std::cout << "After: " << s.capacity() << '\n'; }
Possible output:
Before: 15 After: 100 New capacity: 200 New capacity: 400 New capacity: 800 New capacity: 1600 After: 801
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 847 | C++98 | there was no exception safety guarantee | added strong exception safety guarantee |
returns the number of characters that can be held in currently allocated storage (public member function) |
|
changes the number of characters stored (public member function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/string/basic_string/reserve