cpp / latest / string / basic_string / reserve.html /

std::basic_string<CharT,Traits,Allocator>::reserve

(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)
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 current capacity(), new storage is allocated, and capacity() is made equal or greater than new_cap.
  • If new_cap is less than the current capacity(), this is a non-binding shrink request.
  • If new_cap is less than the current size(), this is a non-binding shrink-to-fit request equivalent to shrink_to_fit() (since C++11).
(until C++20)
  • If new_cap is less than or equal to the current capacity(), there is no effect.
(since C++20)
If a capacity change takes place, all iterators and references, including the past-the-end iterator, are invalidated.
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(). (since C++20)

Parameters

new_cap - new capacity of the string

Return value

(none).

Exceptions

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.

Complexity

At most linear in the size() of the string.

Example

#include <cassert>
#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::string::size_type new_capacity{ 100u };
    std::cout << "Before: " << s.capacity() << "\n";
    assert(new_capacity > s.capacity());
 
    s.reserve(new_capacity);
    std::cout << "After:  " << s.capacity() << "\n";
    assert(new_capacity <= s.capacity());
}

Possible output:

Before: 15
After:  100

See also

returns the number of characters that can be held in currently allocated storage
(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