@@ -374,33 +374,51 @@ impl<T> Rc<T> {
374
374
}
375
375
}
376
376
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.
381
392
///
382
393
/// # Examples
383
394
///
384
395
/// ```
385
- /// #![feature(arc_new_cyclic)]
386
396
/// #![allow(dead_code)]
387
397
/// use std::rc::{Rc, Weak};
388
398
///
389
399
/// struct Gadget {
390
- /// self_weak: Weak<Self>,
391
- /// // ... more fields
400
+ /// me: Weak<Gadget>,
392
401
/// }
402
+ ///
393
403
/// 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()
398
412
/// }
399
413
/// }
400
414
/// ```
415
+ /// [`upgrade`]: Weak::upgrade
401
416
#[ cfg( not( no_global_oom_handling) ) ]
402
- #[ unstable( feature = "arc_new_cyclic" , issue = "75861" ) ]
403
- pub fn new_cyclic ( data_fn : impl FnOnce ( & Weak < T > ) -> T ) -> Rc < T > {
417
+ #[ stable( feature = "arc_new_cyclic" , since = "1.60.0" ) ]
418
+ pub fn new_cyclic < F > ( data_fn : F ) -> Rc < T >
419
+ where
420
+ F : FnOnce ( & Weak < T > ) -> T ,
421
+ {
404
422
// Construct the inner in the "uninitialized" state with a single
405
423
// weak reference.
406
424
let uninit_ptr: NonNull < _ > = Box :: leak ( box RcBox {
0 commit comments