I've recognized that when moving a dereferenced Box
with *Box::new(_)
, it doesn't call Deref::deref
nor DerefMut::deref_mut
; it really moves the value, which means *Box::new(_)
has ownership, not a dereference of a reference.
An example:
let a = Box::new(String::from("hello");
let b = *a;
I've learned that Box
is an extraordinary struct, so that in the case of data move, it actually dereferences like a reference (without Deref
trait).
During the movement, what happens to the memory allocated by
Box
in the heap? Is it freed? Is it replaced with bunch of zeroes? Does it remains only not having any way of being accessed?I know that memory allocated by
String::from
will be freed whenb
drops. I'm not curious of datastr type hello
, I'm curious of memory which would has a size ofsize of String
.How can I explicitly dereference a
Box
withoutDeref
trait? When I try it, it automatically borrowsBox
by callingDeref::deref
.let a = Box::new(String::from("hello")); fn test(i: &String) {} test(&(*a));
The compiler infers that there's no need for moving
*a
, so it seems like it dereferences by the trait, not directly.This case successfully consumes the box and the string:
let a = Box::new(String::from("hello")); fn test(i: String) {} test(*a)