std::string reserve() method
- od C++20
- do C++20
// Non const version onlyconstexpr void reserve( size_type new_cap );// Non const version onlyvoid reserve();
// Non const version onlyvoid reserve( size_type new_cap = 0);
-
(1) Informs a
std::basic_string
object of a planned change in size, so that it can manage the storage allocation appropriately.- If
new_cap
is greater than the currentcapacity()
, new storage is allocated, andcapacity()
is made equal or greater thannew_cap
.- od C++20
- do C++20
- If
new_cap
is less than or equal to the currentcapacity()
, there is no effect.
- If
new_cap
is less than the currentcapacity()
, this is a non-binding shrink request. - If
new_cap
is less than the currentsize()
, this is a non-binding shrink-to-fit request equivalent toshrink_to_fit()
. (od C++11)
- If
-
(2) A call to reserve with no argument is a non-binding shrink-to-fit request. After this call, capacity() has an unspecified value greater than or equal to size().
If a capacity change takes place, all iterators and references, including the past-the-end iterator, are invalidated.
Parameters
new_cap
- new capacity of the string, in number of elements
Type requirements
T
(the container's element type) must meet the requirements ofMoveInsertable
.
Return value
(none)
Complexity
At most linear in the size()
of the container - O(size()).
Exceptions
std::length_error
ifnew_cap > max_size()
- any exception thrown by
Allocator::allocate()
(typicallystd::bad_alloc
)
Example
#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";}
Before: 15After: 100New capacity: 200New capacity: 400New capacity: 800New capacity: 1600After: 801
Hover to see the original license.