Recently I was rereading ISO C++ standard, and found very interesting note:
Note that for
std::vector
, the only constraint on typeT
ofstd::vector<T>
is that typeT
must have copy constructor. Actually, if the memory of vector is full while insertion, is allocate a new memory ofsize = 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];
T
may not have a default constructor?std::vector
do this with "ONLY COPY CONSTRUCTOR?" What implementation and language idioms are used?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.)