In the code below, I use unsafe code to convert an immutable reference into a mutable pointer and then I try to edit the inner value by means of this mutable pointer.
fn main() {
#[repr(transparent)]
struct Item(isize);
impl Item {
#[inline]
fn ptr(&self) -> *mut isize {
self as *const Item as *mut isize
}
fn increment(&self) {
let val = self.0 + 1;
unsafe {std::ptr::write(self.ptr(), val)}
}
}
let item = Item(22);
println!("before = {}", item.0);
item.increment();
println!("after = {}", item.0);
}
When I compile this under debug mode, the results are as expected and the value is indeed incremented. However, under release mode,the value is not incremented at all although that section of the code is run. Also, the following other types of mutating the value don't seem to work either
unsafe {*&mut *(self.ptr()) += 1;}
std::mem::replace()
std::mem::swap()
- What is the reason for this?
- Is what I seek to do impossible under the --release mode?