Does Rc::downgrade decrease strong count?

I'm referring to: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.downgrade

The src shows:

    pub fn downgrade(this: &Self) -> Weak<T> {
        this.inc_weak();
        // Make sure we do not create a dangling Weak
        debug_assert!(!is_dangling(this.ptr));
        Weak { ptr: this.ptr }
    }

based on the code, it seems (1) we do not change strong count, (2) we increase weak count.

This is a bit confusing to me, as the name is not Rc::create_new_weak, but Rc::downgrade (which sounds like we are "changing" a strong to a weak).

Question: does Rc::downgrade change strong count ?

No, it doesn't. It increases the weak count and it leaves the strong count in place.

Don't think in terms of "mutating the strong pointer", because that's not what happens. downgrade merely creates a new weak pointer (and mutates the weak count to keep track of it). It doesn't actively do anything to the originating strong pointer.

1 Like

You can see it from the signature: since it takes a &Rc and not Rc, i.e. it don't consume the passed pointer, the strong count must remain the same. Otherwise it would be decreased twice - on downgrade and on drop - and lead to prematurely freed memory.

2 Likes