Rusty Horse Rusty Horse - 3 months ago 9
C++ Question

C++ memory allocation upon resizing of reserved std::vector

I am curious about the std::vector behavior and I could not find answer anywhere, so ...

Lets have an odd program:

std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.size(); ++i) // OK, I have noticed the mistake in the condition, I am leaving it here for educational purposes
{
vec.resize(vec.size() + 1);
vec[i] = 42;
}


What the behavior in terms of memory allocations will be? Only one allocation upon memory reserving as expected, or resizing clears the memory it does not need?

Answer

For starters this loop will be executed never

std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.size(); ++i)
{
    vec.resize(vec.size() + 1);
    vec[i] = 42;
}

because initially the size of the vector is equal to 0.

Maybe you mean something like the following

std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.capacity(); ++i)
{
    vec.resize(vec.size() + 1);
    vec[i] = 42;
}

In this case the vector will not be reallocated.:)

Here is a demonstrative program

#include <iostream>
#include <vector>

int main()
{
    const size_t N = 5;

    std::vector<int> v;
    v.reserve( N );

    std::vector<int>::size_type i = 0;

    do
    {
        v.resize( v.size() + 1);
        std::cout << v.capacity() << '\t' << v.data() << std::endl;
    } while ( ++i < v.capacity() );

    return 0;
}

Its output might look like

5   0x824da10
5   0x824da10
5   0x824da10
5   0x824da10
5   0x824da10
Comments