E4008
E4008 — A value moved out from behind a reference:let b = *r;whereris a reference to a type that is notCopy. The reference does not own the value, so it cannot give it away. Copy or clone it instead. Amatchon a reference names parts of the value behind it, somatch r { Holder::Full(n) => n }cannot moveneither. Through a raw pointer,let b = *p;andlet b = p[i];are refused when the value has something to drop, since its owner drops it too. Only anunsafe fnsuch ascore::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
Ownership and borrowingThe chapter covering the rule this code enforces.
All diagnosticsEvery code the compiler can emit, grouped by stage.
E4007A value moved while a borrow of it is still used afterwards:
let r = &a; let b = a; followed by a use of r. The borrow would point at a value that has moved away.
E4009An assignment to a variable, or a field or element of it, while a & borrow of it is still used afterwards: let r = &x; x = 2; and then a use of r. The borrow would see the value change under it.