3 ms·
That's not quite true: the reference counts for `Rc` and `shared_ptr` are not stored adjacent to the pointer. In rust these types are guaranteed to be pointer-s
by Diggsey 8y ago
That's not quite true: the reference counts for `Rc` and `shared_ptr` are not stored adjacent to the pointer. In rust these types are guaranteed to be pointer-sized (when the target is Sized) or fat-pointer-sized otherwise.
The reference counts are necessarily stored on the heap at the target of the pointer (the reference count must be shared between all the pointers) pseudocode:
struct RcBox<T> {
strong_count: usize,
weak_count: usize,
value: MaybeInit<T>,
}
Additionally, when you use `into_raw`/`from_raw` you're actually getting a pointer to the value member of the `RcBox` struct (ie. the reference count is stored at a negative offset from that pointer).
- wcrichton 8y agoSure, agreed that they aren't literally adjacent in the struct. My broader point is just that there's a level of indirection which is abstracted over by the Deref trait.
- Rusky 8y ago> there's a level of indirection which is abstracted over by the Deref trait. There isn't, though. Box and Rc have the same number of levels of indirection as the built-in pointers: one. The double * you see in the Box source you linked only arises because the deref method takes self by reference, the same way unique_ptr's operator* takes this as a pointer. (And further, that implementation looks circular? I believe that part of Box is still built-in.) These are both functions that should always be inlined (in fact the unique_ptr implementation I'm looking at goes through at least four functions to retrieve the actual pointer) so any extra address-taking and dereferencing you see is merely compile-time bookkeeping.
- steveklabnik 8y agoIt is! http://manishearth.github.io/blog/2017/01/10/rust-tidbits-box-is-special/ http://manishearth.github.io/blog/2017/01/10/rust-tidbits-bo...
- deleted 8y ago[deleted]