Function std::ptr::read 1.0.0[−][src]
pub unsafe fn read<T>(src: *const T) -> T
Reads the value from src without moving it. This leaves the
memory in src unchanged.
Safety
Behavior is undefined if any of the following conditions are violated:
-
srcmust point to valid, initialized memory. -
srcmust be properly aligned. Useread_unalignedif this is not the case.
Additionally, if T is not Copy, only the returned value or the
pointed-to value can be used or dropped after calling read. read creates
a bitwise copy of T, regardless of whether T: Copy, which can result
in undefined behavior if both copies are used. Note that *src = foo counts
as a use because it will attempt to drop the value previously at *src.
write can be used to overwrite data without causing it to be dropped.
Examples
Basic usage:
let x = 12; let y = &x as *const i32; unsafe { assert_eq!(std::ptr::read(y), 12); }Run
Manually implement mem::swap:
use std::ptr; fn swap<T>(a: &mut T, b: &mut T) { unsafe { // Create a bitwise copy of the value at `a` in `tmp`. let tmp = ptr::read(a); // Exiting at this point (either by explicitly returning or by // calling a function which panics) would cause the value in `tmp` to // be dropped while the same value is still referenced by `a`. This // could trigger undefined behavior if `T` is not `Copy`. // Create a bitwise copy of the value at `b` in `a`. // This is safe because mutable references cannot alias. ptr::copy_nonoverlapping(b, a, 1); // As above, exiting here could trigger undefined behavior because // the same value is referenced by `a` and `b`. // Move `tmp` into `b`. ptr::write(b, tmp); } } let mut foo = "foo".to_owned(); let mut bar = "bar".to_owned(); swap(&mut foo, &mut bar); assert_eq!(foo, "bar"); assert_eq!(bar, "foo");Run