public member function
<string>

std::string::reserve

void reserve (size_t n = 0);
Request a change in capacity
Requests that the string capacity be adapted to a planned change in size to a length of up to n characters.

If n is greater than the current string capacity, the function causes the container to increase its capacity to n characters (or greater).

In all other cases, it is taken as a non-binding request to shrink the string capacity: the container implementation is free to optimize otherwise and leave the string with a capacity greater than n.

This function has no effect on the string length and cannot alter its content.

Parameters

n
Planned length for the string.
Note that the resulting string capacity may be equal or greater than n.
size_t is an unsigned integral type (the same as member type string::size_type).

Return Value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// string::reserve
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::string str;

  std::ifstream file ("test.txt",std::ios::in|std::ios::ate);
  if (file) {
    std::ifstream::streampos filesize = file.tellg();
    str.reserve(filesize);

    file.seekg(0);
    while (!file.eof())
    {
      str += file.get();
    }
    std::cout << str;
  }
  return 0;
}

This example reserves enough capacity in the string object to store an entire file, which is then read character by character. By reserving a capacity for the string of at least the size of the entire file, we try to avoid all the automatic reallocations that the object str could suffer each time that inserting a new character would make its length surpass its capacity.

Complexity

Unspecified, but generally constant.

Iterator validity

Any iterators, pointers and references related to this object may be invalidated.

Data races

The object is modified.

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the string.

If n is greater than the max_size, a length_error exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also