@@ -351,23 +351,31 @@ impl<T> Arc<T> {
351
351
unsafe { Self :: from_inner ( Box :: leak ( x) . into ( ) ) }
352
352
}
353
353
354
- /// Constructs a new `Arc<T>` using a closure `data_fn` that has access to
355
- /// a weak reference to the constructing `Arc<T>` .
354
+ /// Constructs a new `Arc<T>` while giving you a `Weak<T>` to the allocation,
355
+ /// to allow you to construct a `T` which holds a weak pointer to itself .
356
356
///
357
357
/// Generally, a structure circularly referencing itself, either directly or
358
- /// indirectly, should not hold a strong reference to prevent a memory leak.
359
- /// In `data_fn`, initialization of `T` can make use of the weak reference
360
- /// by cloning and storing it inside `T` for use at a later time.
358
+ /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
359
+ /// Using this function, you get access to the weak pointer during the
360
+ /// initialization of `T`, before the `Arc<T>` is created, such that you can
361
+ /// clone and store it inside the `T`.
361
362
///
362
- /// Since the new `Arc<T>` is not fully-constructed until
363
- /// `Arc<T>::new_cyclic` returns, calling [`upgrade`] on the weak
364
- /// reference inside `data_fn` will fail and result in a `None` value.
363
+ /// `new_cyclic` first allocates the managed allocation for the `Arc<T>`,
364
+ /// then calls your closure, giving it a `Weak<T>` to this allocation,
365
+ /// and only afterwards completes the construction of the `Arc<T>` by placing
366
+ /// the `T` returned from your closure into the allocation.
367
+ ///
368
+ /// Since the new `Arc<T>` is not fully-constructed until `Arc<T>::new_cyclic`
369
+ /// returns, calling [`upgrade`] on the weak reference inside your closure will
370
+ /// fail and result in a `None` value.
365
371
///
366
372
/// # Panics
373
+ ///
367
374
/// If `data_fn` panics, the panic is propagated to the caller, and the
368
375
/// temporary [`Weak<T>`] is dropped normally.
369
376
///
370
377
/// # Example
378
+ ///
371
379
/// ```
372
380
/// # #![allow(dead_code)]
373
381
/// use std::sync::{Arc, Weak};
@@ -379,7 +387,12 @@ impl<T> Arc<T> {
379
387
/// impl Gadget {
380
388
/// /// Construct a reference counted Gadget.
381
389
/// fn new() -> Arc<Self> {
382
- /// Arc::new_cyclic(|me| Gadget { me: me.clone() })
390
+ /// // `me` is a `Weak<Gadget>` pointing at the new allocation of the
391
+ /// // `Arc` we're constructing.
392
+ /// Arc::new_cyclic(|me| {
393
+ /// // Create the actual struct here.
394
+ /// Gadget { me: me.clone() }
395
+ /// })
383
396
/// }
384
397
///
385
398
/// /// Return a reference counted pointer to Self.
0 commit comments