Struct alloc::rc::Weak

1.4.0· source[]
pub struct Weak<T: ?Sized> { /* private fields */ }
Expand description

Weak is a version of Rc that holds a non-owning reference to the managed allocation. The allocation is accessed by calling upgrade on the Weak pointer, which returns an Option<Rc<T>>.

Since a Weak reference does not count towards ownership, it will not prevent the value stored in the allocation from being dropped, and Weak itself makes no guarantees about the value still being present. Thus it may return None when upgraded. Note however that a Weak reference does prevent the allocation itself (the backing store) from being deallocated.

A Weak pointer is useful for keeping a temporary reference to the allocation managed by Rc without preventing its inner value from being dropped. It is also used to prevent circular references between Rc pointers, since mutual owning references would never allow either Rc to be dropped. For example, a tree could have strong Rc pointers from parent nodes to children, and Weak pointers from children back to their parents.

The typical way to obtain a Weak pointer is to call Rc::downgrade.

Implementations

Constructs a new Weak<T>, without allocating any memory. Calling upgrade on the return value always gives None.

Examples
use std::rc::Weak;

let empty: Weak<i64> = Weak::new();
assert!(empty.upgrade().is_none());
Run

Returns a raw pointer to the object T pointed to by this Weak<T>.

The pointer is valid only if there are some strong references. The pointer may be dangling, unaligned or even null otherwise.

Examples
use std::rc::Rc;
use std::ptr;

let strong = Rc::new("hello".to_owned());
let weak = Rc::downgrade(&strong);
// Both point to the same object
assert!(ptr::eq(&*strong, weak.as_ptr()));
// The strong here keeps it alive, so we can still access the object.
assert_eq!("hello", unsafe { &*weak.as_ptr() });

drop(strong);
// But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
// undefined behaviour.
// assert_eq!("hello", unsafe { &*weak.as_ptr() });
Run

Consumes the Weak<T> and turns it into a raw pointer.

This converts the weak pointer into a raw pointer, while still preserving the ownership of one weak reference (the weak count is not modified by this operation). It can be turned back into the Weak<T> with from_raw.

The same restrictions of accessing the target of the pointer as with as_ptr apply.

Examples
use std::rc::{Rc, Weak};

let strong = Rc::new("hello".to_owned());
let weak = Rc::downgrade(&strong);
let raw = weak.into_raw();

assert_eq!(1, Rc::weak_count(&strong));
assert_eq!("hello", unsafe { &*raw });

drop(unsafe { Weak::from_raw(raw) });
assert_eq!(0, Rc::weak_count(&strong));
Run

Converts a raw pointer previously created by into_raw back into Weak<T>.

This can be used to safely get a strong reference (by calling upgrade later) or to deallocate the weak count by dropping the Weak<T>.

It takes ownership of one weak reference (with the exception of pointers created by new, as these don’t own anything; the method still works on them).

Safety

The pointer must have originated from the into_raw and must still own its potential weak reference.

It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this takes ownership of one weak reference currently represented as a raw pointer (the weak count is not modified by this operation) and therefore it must be paired with a previous call to into_raw.

Examples
use std::rc::{Rc, Weak};

let strong = Rc::new("hello".to_owned());

let raw_1 = Rc::downgrade(&strong).into_raw();
let raw_2 = Rc::downgrade(&strong).into_raw();

assert_eq!(2, Rc::weak_count(&strong));

assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
assert_eq!(1, Rc::weak_count(&strong));

drop(strong);

// Decrement the last weak count.
assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
Run

Attempts to upgrade the Weak pointer to an Rc, delaying dropping of the inner value if successful.

Returns None if the inner value has since been dropped.

Examples
use std::rc::Rc;

let five = Rc::new(5);

let weak_five = Rc::downgrade(&five);

let strong_five: Option<Rc<_>> = weak_five.upgrade();
assert!(strong_five.is_some());

// Destroy all strong pointers.
drop(strong_five);
drop(five);

assert!(weak_five.upgrade().is_none());
Run

Gets the number of strong (Rc) pointers pointing to this allocation.

If self was created using Weak::new, this will return 0.

Gets the number of Weak pointers pointing to this allocation.

If no strong pointers remain, this will return zero.

Returns true if the two Weaks point to the same allocation (similar to ptr::eq), or if both don’t point to any allocation (because they were created with Weak::new()).

Notes

Since this compares pointers it means that Weak::new() will equal each other, even though they don’t point to any allocation.

Examples
use std::rc::Rc;

let first_rc = Rc::new(5);
let first = Rc::downgrade(&first_rc);
let second = Rc::downgrade(&first_rc);

assert!(first.ptr_eq(&second));

let third_rc = Rc::new(5);
let third = Rc::downgrade(&third_rc);

assert!(!first.ptr_eq(&third));
Run

Comparing Weak::new.

use std::rc::{Rc, Weak};

let first = Weak::new();
let second = Weak::new();
assert!(first.ptr_eq(&second));

let third_rc = Rc::new(());
let third = Rc::downgrade(&third_rc);
assert!(!first.ptr_eq(&third));
Run

Trait Implementations

Makes a clone of the Weak pointer that points to the same allocation.

Examples
use std::rc::{Rc, Weak};

let weak_five = Rc::downgrade(&Rc::new(5));

let _ = Weak::clone(&weak_five);
Run

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Constructs a new Weak<T>, without allocating any memory. Calling upgrade on the return value always gives None.

Examples
use std::rc::Weak;

let empty: Weak<i64> = Default::default();
assert!(empty.upgrade().is_none());
Run

Drops the Weak pointer.

Examples
use std::rc::{Rc, Weak};

struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("dropped!");
    }
}

let foo = Rc::new(Foo);
let weak_foo = Rc::downgrade(&foo);
let other_weak_foo = Weak::clone(&weak_foo);

drop(weak_foo);   // Doesn't print anything
drop(foo);        // Prints "dropped!"

assert!(other_weak_foo.upgrade().is_none());
Run

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.