About std::vector::resize().

Martin Sebor sebor@roguewave.com
Tue May 25 19:50:00 GMT 2004


Theodore Papadopoulo wrote:

> sebor@roguewave.com said:
> 
>>>One could implement a resize from size m to size n (n > m) as:
>>>
>>>- Create new vector with size n, using the default constructor
>>>  for all elements.
>>>- Swap the first m elements.
>>>- Destroy the old vector.
> 
> 
>>That's not allowed by 23.2.4.2, p5:
>>     It is guaranteed that no reallocation takes place during
>>     insertions that happen after a call to reserve() until the
>>     time when an insertion would make the size of the vector
>>     greater than the size specified in the most recent call
>>     to reserve(). 
> 
> 
> I'm certainly dense tonight, but I do not see where reallocation
> happen in the algorithm sketched above...
> 
> - Creating the vector is necessary (unless the size is already bigger 
> than n, but this is not the case of interest here). This is where 
> reserve is called.

The code below must not abort for any (n > 0) but if resize()
constructed a new vector and swapped *this for it, it would.

     std::vector<T> v;
     v.resize (1);
     v.reserve (n);
     T *p = &v [0];
     v.resize (n);   // must not reallocate
     assert (&v [0] == p);

(I see gave the wrong reference above, but the requirement not to
reallocate unless the new size would exceed the current capacity
applies to all member functions, including resize() and insert()).

Martin



More information about the Libstdc++ mailing list