-1

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).

  1. 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 when b drops. I'm not curious of data str type hello, I'm curious of memory which would has a size of size of String.

  2. How can I explicitly dereference a Box without Deref trait? When I try it, it automatically borrows Box by calling Deref::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)
    
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
kwonryul
  • 481
  • 3
  • 10
  • 1
    It's hard to answer multiple questions made in one post. Please separate them into multiple questions so that we can help you better and so that your questions will help others in the future that have one of the same questions as you! – Shepmaster Jan 04 '21 at 16:02
  • Your question might be answered by the answers of [How can I reuse a box that I have moved the value out of?](https://stackoverflow.com/q/38397163/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jan 04 '21 at 16:04

1 Answers1

5

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).

It doesn't, which is rather the point. Box alone has access to an intrinsic "deref move" feature which is not actually formalised or otherwise available.

During the movement, what happens to the memory allocated by Box in the heap? Is it freed?

Yes.

How can I explicitly dereference a Box without Deref trait?

By using *.

test(&(*a));

The parens do nothing useful here, this just reborrows the pointee.

Replacing the parens by braces would force moving the dereferenced value.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Wow! It's now clear. Thank you!! Making it expression seems the best! ( It was just for my curiosity, though lol) – kwonryul Jan 04 '21 at 17:15