Remove elements without losing capacity

Riccardo M asd at asd.asd
Tue Oct 4 21:13:07 UTC 2022


On Tuesday, 4 October 2022 at 18:18:41 UTC, Ali Çehreli wrote:
> On 10/4/22 10:59, Riccardo M wrote:
>
> > The inherent reason for `remove` to cancel previous capacity
> and
> > requiring new allocations is exactly to prevent overwriting
> data that
> > could be owned by something else?
>
> Yes.
>
> A related topic is how the "end slice" never loses that 
> capacity:
>
> void main() {
>     auto a = [ 1, 2 ];
>     auto b = a;
>
>     assert(a.capacity != 0);
>     assert(b.capacity != 0);
>
>     b.length--;
>     assert(b.capacity == 0);
>     assert(a.capacity != 0);    // <-- Preserved
> }
>
> Aside: .capacity is an expensive operation that requires some 
> levels of table lookups in the druntime. A data structure would 
> benefit a lot if it kept its own capacity as a member variable.
>
> Ali

Wonderful. Thanks for the insight,


More information about the Digitalmars-d-learn mailing list