This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: About std::vector::resize().
- From: Martin Sebor <sebor at roguewave dot com>
- To: libstdc++ <libstdc++ at gcc dot gnu dot org>
- Date: Tue, 25 May 2004 13:05:04 -0600
- Subject: Re: About std::vector::resize().
- References: <200405251846.i4PIkBZP032335@mururoa.inria.fr>
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