@@ -1022,6 +1022,30 @@ impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
1022
1022
///
1023
1023
/// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
1024
1024
///
1025
+ /// ## out-pointers
1026
+ ///
1027
+ /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
1028
+ /// from a function, pass it a pointer to some (uninitialized) memory to put the
1029
+ /// result into. This can be useful when it is important for the caller to control
1030
+ /// how the memory the result is stored in gets allocated, and you want to avoid
1031
+ /// unnecessary moves.
1032
+ ///
1033
+ /// ```
1034
+ /// use std::mem::MaybeUninit;
1035
+ ///
1036
+ /// unsafe fn make_vec(out: *mut Vec<i32>) {
1037
+ /// // `write` does not drop the old contents, which is important.
1038
+ /// out.write(vec![1, 2, 3]);
1039
+ /// }
1040
+ ///
1041
+ /// let mut v: MaybeUninit<Vec<i32>> = MaybeUninit::uninit();
1042
+ /// unsafe { make_vec(v.as_mut_ptr()); }
1043
+ /// // Now we know `v` is initialized! This also makes sure the vector gets
1044
+ /// // properly dropped.
1045
+ /// let v = unsafe { v.assume_init() };
1046
+ /// assert_eq!(&v, &[1, 2, 3]);
1047
+ /// ```
1048
+ ///
1025
1049
/// ## Initializing an array element-by-element
1026
1050
///
1027
1051
/// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
@@ -1049,7 +1073,7 @@ impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
1049
1073
/// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
1050
1074
/// };
1051
1075
///
1052
- /// println!("{:?}", &data[0]);
1076
+ /// assert_eq!( &data[0], &[42 ]);
1053
1077
/// ```
1054
1078
///
1055
1079
/// You can also work with partially initialized arrays, which could
0 commit comments