I have recently read the article by Arthur Carcano about transient droppers and something is bugging me about the code sample he provides :
let mut ptr_i = uninit_array.as_mut_ptr() as *mut T; // Look here...
let mut transient_dropper = TransientDropper {
base_ptr: ptr_i, // Here...
initialized_count: 0,
};
let array : Option<[T;5]> = unsafe {
for i in 0..5 {
let value_i = f(i).unwrap();
ptr_i.write(value_i); // here
ptr_i = ptr_i.add(1); // and here
transient_dropper.initialized_count += 1;
}
mem::forget(transient_dropper);
Some(uninit_array.assume_init())
};
The code sample compiles fines so this is a post to align my view of ownership not to criticize his work.
If you look at my comments from top to bottom, here is my issue :
"How is it possible that he defines a value (even if it is a pointer), assign it to a field of a structure then proceeds to modify it twice outside of the said structure (he is not accessing the value from the "struct namespace") ?"
Should not the value have moved after having assigned it to the structure ?
I have read the write
function's documentation but it says "Overwrites a memory location with the given value without reading or dropping the old value" so it does tell me that it does not affect the pointer (and by then not consuming it ?) but is not the ptr_i = ptr_i.add(1);
doing exactly that (as its declaration consumes self : fn add(self, count: usize) ...
)?
Once again I am trying to piece out the details, not making any claims. I do not know what rules apply in unsafe blocks or to pointers so I am trying to acquire knowledge.