Does comment on Rc<T>.as_ptr() imply Rc<T> is always pinned?

Hi Folks,

I found comments in Rc<T>.as_ptr() mentioned:

The pointer is valid for as long there are strong counts in the Rc.

Does that mean the value held by Rc will never be moved? If so does Rc<T> is equivalent to Pin<Rc<T>>? Also, how is that related to method?

Thanks for any explanations!

1 Like

Rc is not pinned (without Pin<Rc>) because of Rc::as_mut and Rc::make_mut, which give you access to &mut T, which breaks pinning guarantees (allows access to mem::swap).

No. That means the value held by Rc will never be invalid, but it may not be the same - i.e., the pointer acquired via as_ptr will always point on some T (as long as there's at least one Rc alive), but non necessarily on the same T it pointed at the moment of creation.

Whether Rc::as_ptr provides sufficient pinning guarantees for your use-case depends on how it is used. The other comments give some examples for how the value in the Rc might get swapped, so if arbitrary safe user-code has access to the Rc, then you can't expect the value to not get swapped out. However, if your code doesn't give out the Rc to user-code, and you don't call make_mut yourself, then yes, the value will stay put and relying on that in unsafe code is perfectly fine.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.