std::string reserve() method
- od C++20
- do C++20
// Non const version only
constexpr void reserve( size_type new_cap );
// Non const version only
void reserve();
// Non const version only
void 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().
Invalidation
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
Main.cpp
#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
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.