Why does the documentation of std::ptr::read state that ptr::copy_nonoverlapping "could trigger undefined behavior"?

Viewed 87

The documentation of std::ptr::read has this example code:

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);

        // `tmp` has been moved (`write` takes ownership of its second argument),
        // so nothing is dropped implicitly here.
    }
}

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");

I concern about this part:

    ptr::copy_nonoverlapping(b, a, 1);

    // As above, exiting here could trigger undefined behavior because
    // the same value is referenced by `a` and `b`.

In my opinion, a: &mut T and b: &mut T point to two different blocks of memory. Why does it say "the same value is referenced by a and b", then to trigger undefined behavior? Did I miss something?

1 Answers

I missed an important annotation:

// Create a bitwise copy of the value at `a` in `tmp`.
let tmp = ptr::read(a);

// #################### Marked by me
// 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`.
// #################### Marked by me

It is operating on some data of type T which may hold managed resource (such as memory on the heap, file handles, etc.) and not be Copy (such as String), so this bitwise copy operation would result in two T data holders sharing the common resource, which could trigger undefined behavior.

Related