@@ -1540,6 +1540,12 @@ fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1540
1540
/// let raw_f2 = ptr::addr_of!(packed.f2);
1541
1541
/// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1542
1542
/// ```
1543
+ ///
1544
+ /// See [`addr_of_mut`] for how to create a pointer to ininitialized data.
1545
+ /// Doing that with `addr_of` would not make much sense since one could only
1546
+ /// read the data, and that would be Undefined Behavior.
1547
+ ///
1548
+ /// [`addr_of_mut`]: macro.addr_of_mut.html
1543
1549
#[ stable( feature = "raw_ref_macros" , since = "1.51.0" ) ]
1544
1550
#[ rustc_macro_transparency = "semitransparent" ]
1545
1551
#[ allow_internal_unstable( raw_ref_op) ]
@@ -1556,7 +1562,9 @@ pub macro addr_of($place:expr) {
1556
1562
/// as all other references. This macro can create a raw pointer *without* creating
1557
1563
/// a reference first.
1558
1564
///
1559
- /// # Example
1565
+ /// # Examples
1566
+ ///
1567
+ /// **Creating a pointer to unaligned data:**
1560
1568
///
1561
1569
/// ```
1562
1570
/// use std::ptr;
@@ -1573,6 +1581,23 @@ pub macro addr_of($place:expr) {
1573
1581
/// unsafe { raw_f2.write_unaligned(42); }
1574
1582
/// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1575
1583
/// ```
1584
+ ///
1585
+ /// **Creating a pointer to uninitialized data:**
1586
+ ///
1587
+ /// ```rust
1588
+ /// use std::{ptr, mem::MaybeUninit};
1589
+ ///
1590
+ /// struct Demo {
1591
+ /// field: bool,
1592
+ /// }
1593
+ ///
1594
+ /// let mut uninit = MaybeUninit::<Demo>::uninit();
1595
+ /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1596
+ /// // and thus be Undefined Behavior!
1597
+ /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1598
+ /// unsafe { f1_ptr.write(true); }
1599
+ /// let init = unsafe { uninit.assume_init() };
1600
+ /// ```
1576
1601
#[ stable( feature = "raw_ref_macros" , since = "1.51.0" ) ]
1577
1602
#[ rustc_macro_transparency = "semitransparent" ]
1578
1603
#[ allow_internal_unstable( raw_ref_op) ]
0 commit comments