C++ Logo

std-proposals

Advanced search

Re: [std-proposals] New function for std::vector

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sat, 4 Jan 2025 10:26:05 -0500
On Fri, Dec 27, 2024 at 7:12 PM Jonathan Wakely via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Fri, 27 Dec 2024, 22:51 Chris Ryan via Std-Proposals, <
> std-proposals_at_[hidden]> wrote:
>
>> Hi Andre,
>> .resize(0) actually deletes the storage.
>>
>
> No it doesn't. clear() and resize(0) both preserve capacity.
>
> Farrakh is wanting it to preserve the storage (keep the .capacity(), not
>> have to alloc it again)
>>
>
> That's what clear() does.
>

Tangent, FWIW: Everything Jonathan said is portably true for `vector`; but
for other containers the answers are different and/or vendor-dependent.
https://quuxplusone.github.io/blog/2025/01/02/shrink-to-fit/#how-do-i-clear-and-free-in-one-line
I wrote this post from the POV of "How do I *get rid* of the allocation"
rather than "How do I *keep* the allocation," but the table answers both
questions:
To reliably free the allocation: `V().swap(v)`
To reliably keep it: `v.resize(0)` or `v = {}`

–Arthur

Received on 2025-01-04 15:26:20