About std::vector::resize().

Jerry Quinn jlquinn@optonline.net
Tue May 25 22:22:00 GMT 2004


Martin Sebor writes:
 > 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()).

We can just do the trick when a reallocation would be necessary, so
the above would still work, no?

Jerry Quinn



More information about the Libstdc++ mailing list