Closed
Description
openedon Nov 29, 2023
This code gets rejected, and (as far as I can tell) not for good reasons:
#![feature(const_mut_refs)]
#[repr(C)]
struct Foo {
v: u32,
}
#[repr(C)]
struct Bar {
foo: *mut Foo,
}
unsafe impl Sync for Bar {}
extern "C" {
static mut foo: Foo;
}
fn do_it() {
static BAR: Bar = Bar {
foo: unsafe { core::ptr::addr_of_mut!(foo)},
};
}
The error is
error[E0764]: raw mutable references are not allowed in the final value of statics
--> src/lib.rs:21:23
|
21 | foo: unsafe { core::ptr::addr_of_mut!(foo)},
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
This error is meant to catch cases like this
static BAR: Bar = Bar {
foo: &mut Foo { v: 0 },
};
where a temporary (Foo { v: 0 }
) escapes into the final value of the constant. However, for the original code there's no temporary, this is a pointer to a static
.
Here's an executable pure Rust version (no extern).
It seems to me we could allow mutable pointers to already existing (mutable) allocations to leak out into the final const value. However we should carefully consider the consequences of this. I can't think of anything that would go wrong here right now, but that might be just a sign of sleep deprivation. ;)
Cc @rust-lang/wg-const-eval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment