New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Weak::{strong_count, weak_count} #56696

wants to merge 2 commits into
base: master


None yet
5 participants
Copy link

jonas-schievink commented Dec 10, 2018

The counters are also useful on Weak, not just on strong references (Rc or Arc).

In situations where there are still strong references around, you can also get these counts by temporarily upgrading and adjusting the values accordingly. Using the methods introduced here is simpler to do, less error-prone (since you can't forget to adjust the counts), can also be used when no strong references are around anymore, and might be more efficient due to not having to temporarily create an Rc.

This is mainly useful in assertions or tests of complex data structures. Data structures might have internal invariants that make them the sole owner of a Weak pointer, and an assertion on the weak count could be used to ensure that this indeed happens as expected. Due to the presence of Weak::upgrade, the strong_count becomes less useful, but it still seems worthwhile to mirror the API of Rc.


  • Tracking issue
  • Unstable book entry

This comment has been minimized.

Copy link

rust-highfive commented Dec 10, 2018

r? @KodrAus

(rust_highfive has picked a reviewer for you, use r? to override)

// Due to the implicit weak pointer added when any strong pointers are
// around, we cannot implement `weak_count` correctly since it necessarily
// requires accessing the strong count and weak count in an unsynchronized
// fashion.

This comment has been minimized.


jonas-schievink Dec 10, 2018


I've added a strong_count method to sync::Weak as well, but here the tradeoff is less clear since (I think) weak_count can not be implemented correctly, so the API must stay asymmetric like this (or not offer strong_count at all, since it isn't very useful)


This comment has been minimized.

Copy link

Dylan-DPC commented Jan 7, 2019

ping from triage, can anyone from @rust-lang/libs review this?


This comment has been minimized.

Copy link

alexcrichton commented Jan 7, 2019

Having a discrepancy in weak_count is sort of a bummer, would it be possible to implement, even a racy version, on Arc? Otherwise shouldn't weak_count on a Weak always return >= 1?

@jonas-schievink jonas-schievink force-pushed the jonas-schievink:weak-counts branch from 3ac71b0 to 3dbd7fc Jan 7, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment