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];
- How this is done, because the type
T
may not have a default constructor? - Then Assignment, after allocating the memory we must assign old values to new memory, right?
- To taking into consideration this 2 things, how does
std::vector
do this with "ONLY COPY CONSTRUCTOR?" What implementation and language idioms are used?
new
. Array-new
is a complete misfeature of the language and utterly useless, as you're just discovering. Instead, memory allocation and object construction are done completely separately from one another. – Calyxnew
is good for allocating arrays. You can argue that explicit manual allocation is bad (in which case you are againstnew
,delete
,new[]
anddelete[]
and likely raw pointers as well), but that's different from arguing that only array-new
is bad. – Fairmindedstd::vector
. – Calyxvoid*
is also "conceptually broken" because you need to remember the type of the thing pointed to. – Fairmindednew[]
lets you allocate several contiguous PODs (or even full objects). For that purpose it works just fine. – Fairminded