https://gcc.gnu.org/bugzilla/show_bug.cgi?id=119323

--- Comment #4 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to Jonathan Wakely from comment #3)
> Why is the new array allocated for 1 + input.nec items?

Ah, I bet it's to handle the case where input.nec == 0. But that's not needed,
C++ allows new T[n] even when n==0.

> The std::fill does nothing. It copies from where the std::copy finished to
> ... where the std::copy finished. Maybe it was meant to init the extra
> element in the array? But why is that extra element even there?

Ah, maybe it's supposed to clear any trailing elements in the case where nec >
input.nec, but it fails to do that, because it uses ecs + input.nec as the end,
not ecs + nec. And if it used ecs + nec that would be wrong, because if we
reallocated a new array then nec will still refer to the old length.

In the case where nec > input.nec, we do not reallocate (because we don't need
to) but then the original size of the allocation is forgotten because of the
'nec = input.nec' assignment at the end. That means if we initially have 10
elements, then assign a smaller object with 5 elements, then assign another one
with 6, it will allocate a new array despite actually having capacity for 10
elements.

Why not just use std::vector here to manage the array? That will correctly
handle keeping track of available, unused capacity, and clearing old elements
at the end when assigning a smaller object.

Reply via email to