E4008

E4008 — A value moved out from behind a reference: let b = *r; where r is a reference to a type that is not Copy. The reference does not own the value, so it cannot give it away. Copy or clone it instead. A match on a reference names parts of the value behind it, so match r { Holder::Full(n) => n } cannot move n either. Through a raw pointer, let b = *p; and let b = p[i]; are refused when the value has something to drop, since its owner drops it too. Only an unsafe fn such as core::ptr::read(p) may take it out.

What the compiler reports

Error[E4008] at {{.*}}.vx:29:20: this moves a value of type `Noisy` out from behind a raw pointer
Error[E4008] at {{.*}}.vx:35:21: this moves a value of type `Noisy` out from behind a raw pointer
2 error(s) emitted

The fragments the test suite holds the compiler to. An ellipsis marks text the test does not constrain; the emitted message also carries a source location.

A program that triggers it

//
// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//
// `*p` and `p[0]` read by value through a raw pointer would move the value out while its
// owner still drops it, so it would be dropped twice (E4008).

struct Noisy {
  id : i32,
}

impl Drop for Noisy {
  fn drop(self : &mut Noisy) -> void {
    print!("d{} ", self.id);
  }
}

fn read_with_a_star(p : *const Noisy) -> i32 {
  let mut k = 0;
  unsafe { let v = *p; k = v.id; }
  return k;
}

fn read_with_an_index(p : *const Noisy) -> i32 {
  let mut k = 0;
  unsafe { let v = p[0]; k = v.id; }
  return k;
}

fn main() -> i32 {
  let o = Noisy {
    id: 3
  };
  let p = (&o) as *const Noisy;
  return read_with_a_star(p) + read_with_an_index(p);
}

From tests/frontend/fail/moving_a_value_out_through_a_raw_pointer.vx, which asserts this diagnostic on every commit.

Related