Closed yanchith closed 10 months ago
If memory gets reused, the allocator must be kept. No questions here.
I would say that it is "implementation defined": the collection can either reuse the existing allocator, or clone the allocator from the source. The latter can happen when deriving Clone
(#98374) since that will use the default implementation of clone_from
which simply calls clone
and replaces the existing value.
Thank you for both of your answers. This totally makes sense, and was an interesting exercise to think about. I ended up not cloning the allocator in clone_from
, as that would almost certainly be incorrect in my case.
Closing this. Hopefully it will be useful to someone in the future.
Should
Collection::clone_from(&mut self, other: &Self)
keep the original allocator, or should it clone it fromother
? The way the trait is defined allows for cloning (A: Clone
), but on some deeper level this makes me uneasy. I have always interpreted clone_from as "reuse memory from self, but clone the data from other", and I wouldn't expect a collection's allocator to ever change once it is initialized.Had a cursory look at liballoc and hashbrown, and neither seems to clone the allocator? On the other hand, there's nothing that formally prevents them from doing so?
The more I think about this, the more I think that it should not clone. If nothing else, if the two allocators are actually different, they wouldn't know what to do with each other's pointers for resizing/deallocating. Maybe this is worth documenting?
Context: I am writing a BucketArray style collection (sometimes also called a Slab) to help with growing behavior on bump allocators.