@@ -1537,6 +1537,10 @@ fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1537
1537
/// as all other references. This macro can create a raw pointer *without* creating
1538
1538
/// a reference first.
1539
1539
///
1540
+ /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
1541
+ /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
1542
+ /// Behavior because it dereferences a NULL pointer.
1543
+ ///
1540
1544
/// # Example
1541
1545
///
1542
1546
/// ```
@@ -1553,6 +1557,10 @@ fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1553
1557
/// let raw_f2 = ptr::addr_of!(packed.f2);
1554
1558
/// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1555
1559
/// ```
1560
+ ///
1561
+ /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
1562
+ /// Doing that with `addr_of` would not make much sense since one could only
1563
+ /// read the data, and that would be Undefined Behavior.
1556
1564
#[ stable( feature = "raw_ref_macros" , since = "1.51.0" ) ]
1557
1565
#[ rustc_macro_transparency = "semitransparent" ]
1558
1566
#[ allow_internal_unstable( raw_ref_op) ]
@@ -1569,7 +1577,13 @@ pub macro addr_of($place:expr) {
1569
1577
/// as all other references. This macro can create a raw pointer *without* creating
1570
1578
/// a reference first.
1571
1579
///
1572
- /// # Example
1580
+ /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
1581
+ /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
1582
+ /// Behavior because it dereferences a NULL pointer.
1583
+ ///
1584
+ /// # Examples
1585
+ ///
1586
+ /// **Creating a pointer to unaligned data:**
1573
1587
///
1574
1588
/// ```
1575
1589
/// use std::ptr;
@@ -1586,6 +1600,23 @@ pub macro addr_of($place:expr) {
1586
1600
/// unsafe { raw_f2.write_unaligned(42); }
1587
1601
/// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1588
1602
/// ```
1603
+ ///
1604
+ /// **Creating a pointer to uninitialized data:**
1605
+ ///
1606
+ /// ```rust
1607
+ /// use std::{ptr, mem::MaybeUninit};
1608
+ ///
1609
+ /// struct Demo {
1610
+ /// field: bool,
1611
+ /// }
1612
+ ///
1613
+ /// let mut uninit = MaybeUninit::<Demo>::uninit();
1614
+ /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1615
+ /// // and thus be Undefined Behavior!
1616
+ /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1617
+ /// unsafe { f1_ptr.write(true); }
1618
+ /// let init = unsafe { uninit.assume_init() };
1619
+ /// ```
1589
1620
#[ stable( feature = "raw_ref_macros" , since = "1.51.0" ) ]
1590
1621
#[ rustc_macro_transparency = "semitransparent" ]
1591
1622
#[ allow_internal_unstable( raw_ref_op) ]
0 commit comments