@@ -374,32 +374,47 @@ impl<T> Rc<T> {
374374 }
375375 }
376376
377- /// Constructs a new `Rc<T>` using a weak reference to itself. Attempting
378- /// to upgrade the weak reference before this function returns will result
379- /// in a `None` value. However, the weak reference may be cloned freely and
380- /// stored for use at a later time.
377+ /// Constructs a new `Rc<T>` using a closure `data_fn` that has access to a
378+ /// weak reference to the constructing `Rc<T>`.
379+ ///
380+ /// Generally, a structure circularly referencing itself, either directly or
381+ /// indirectly, should not hold a strong reference to prevent a memory leak.
382+ /// In `data_fn`, initialization of `T` can make use of the weak reference
383+ /// by cloning and storing it inside `T` for use at a later time.
384+ ///
385+ /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
386+ /// returns, calling [`upgrade`] on the weak reference inside `data_fn` will
387+ /// fail and result in a `None` value.
388+ ///
389+ /// # Panics
390+ /// If `data_fn` panics, the panic is propagated to the caller, and the
391+ /// temporary [`Weak<T>`] is dropped normally.
381392 ///
382393 /// # Examples
383394 ///
384395 /// ```
385- /// #![feature(arc_new_cyclic)]
386396 /// #![allow(dead_code)]
387397 /// use std::rc::{Rc, Weak};
388398 ///
389399 /// struct Gadget {
390- /// self_weak: Weak<Self>,
391- /// // ... more fields
400+ /// me: Weak<Gadget>,
392401 /// }
402+ ///
393403 /// impl Gadget {
394- /// pub fn new() -> Rc<Self> {
395- /// Rc::new_cyclic(|self_weak| {
396- /// Gadget { self_weak: self_weak.clone(), /* ... */ }
397- /// })
404+ /// /// Construct a reference counted Gadget.
405+ /// fn new() -> Rc<Self> {
406+ /// Rc::new_cyclic(|me| Gadget { me: me.clone() })
407+ /// }
408+ ///
409+ /// /// Return a reference counted pointer to Self.
410+ /// fn me(&self) -> Rc<Self> {
411+ /// self.me.upgrade().unwrap()
398412 /// }
399413 /// }
400414 /// ```
415+ /// [`upgrade`]: Weak::upgrade
401416 #[ cfg( not( no_global_oom_handling) ) ]
402- #[ unstable ( feature = "arc_new_cyclic" , issue = "75861 " ) ]
417+ #[ stable ( feature = "arc_new_cyclic" , since = "1.59.0 " ) ]
403418 pub fn new_cyclic ( data_fn : impl FnOnce ( & Weak < T > ) -> T ) -> Rc < T > {
404419 // Construct the inner in the "uninitialized" state with a single
405420 // weak reference.
0 commit comments