简体   繁体   中英

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

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM