Why does BTreeSet use ManuallyDrop?

From set.rs - source

    fn sub(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
        BTreeSet::from_sorted_iter(
            self.difference(rhs).cloned(),
            ManuallyDrop::into_inner(self.map.alloc.clone()),
        )
    }

I don't understand what is going on here.

Have you seen the comment here? map.rs - source

    /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
    // Although some of the accessory types store a copy of the allocator, the nodes do not.
    // Because allocations will remain live as long as any copy (like this one) of the allocator
    // is live, it's unnecessary to store the allocator in each node.
    pub(super) alloc: ManuallyDrop<A>,

The function ManuallyDrop::into_inner destroys the ManuallyDrop and takes the inner object out of it. Down the Calltree (map.rs - source) you can see that a new ManuallyDrop with the Allocator is created. So this is just to satisfy the function signature.

1 Like

Thanks, I had not seen it, I now understand ( at least roughly ) what is going on. I had mis-read the code, which contributed to my confusion.