Search code examples
c++vectorstlcopy-constructorassignment-operator

How is std::vector insert implemented? C++


Recently I was rereading ISO C++ standard, and found very interesting note:

Note that for std::vector, the only constraint on type T of std::vector<T> is that type T must have copy constructor. Actually, if the memory of vector is full while insertion, is allocate a new memory of size = 2 * oldSize (this is implementation dependent) and then copy old elements in it and insert that one element.

But Wait??

To allocate new memory of type the we need something like this, ptr = new T[2*size];

  1. How this is done, because the type T may not have a default constructor?
  2. Then Assignment, after allocating the memory we must assign old values to new memory, right?
  3. To taking into consideration this 2 things, how does std::vector do this with "ONLY COPY CONSTRUCTOR?" What implementation and language idioms are used?

Solution

  • As a general rule, the standard containers separate allocation from initialization (as should any containers you write too). The standard containers use a very complex mechanism in order to allow customization of both allocation and initialization, but in the default case, it boils down to using the operator new/operator delete functions to allocate the memory, placement new to initialize it, and an explicit call to the destructor to destroy the objects. In other words, insteaad of the sequence:

    p = new T[n];
    //  ...
    delete [] p;
    

    it uses:

    p = operator new( n * sizeof( T ) );
    for ( int i = 0; i != n; ++ i ) {
        new ( p + i ) T( otherValue );
    }
    
    //  ...
    for ( int i = 0; i != n; ++ i ) {
        p->~T();
    }
    operator delete( p );
    

    (This is a radical simplification, to show the basic concept. In practice, it will be more complex, for reasons of exception safety, for example.)