H-005
H-005

Reputation: 505

How does std::vector::reserve actually work?

I understand that .reserve() reserves memory for the vector without actually modifying its size. But how is this implemented? How can you just reserve memory without allocating it?

EDIT: I'm asking specifically about how to reserve memory without allocating it, not about how std::vector works in general

Upvotes: 2

Views: 3189

Answers (3)

Pete Becker
Pete Becker

Reputation: 76305

The size of a vector is the number of elements that it holds. The capacity of a vector is the number of elements that it could hold without allocating additional memory. reserve can increase the capacity by reallocating and copying the elements. That increases the capacity but doesn’t change the size.

Upvotes: 1

NutCracker
NutCracker

Reputation: 12263

You misunderstood one main thing: std::vector::reserve actually allocates memory.

Let's say we create a custom Allocator like:

template <typename T>
struct Allocator
{
    using value_type = T;

    Allocator() = default;
 
    T* allocate( std::size_t N )
    {
        N *= sizeof( T );
        std::cout << "Allocation " << N << " bytes" << std::endl;
        return static_cast< T* >( ::operator new( N ) );
    }
 
    void deallocate( T *ptr, std::size_t N ) 
    {
        std::cout << "Deallocation " << (N * sizeof * ptr) << " bytes" << std::endl;
        ::operator delete( ptr );
    }
};

If you use it like:

int main()
{
    std::vector< int, Allocator< int > > v;
    v.reserve( 100 );
}

The output would be:

Allocation 400 bytes
Deallocation 400 bytes

You can play with it here.

Upvotes: 3

john
john

Reputation: 87959

vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect. The point is that reserving memory can be done without changing the vectors size. Basically a vector has two sizes, it's size and it's capacity. reserve allocates memory and changes the capacity, but not the size.

At any given time the following is true 0 <= size <= capacity. The capacity reflects the amount of memory allocated, the size reflects the number of constructed elements in that memory.

Upvotes: 8

Related Questions