How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable?

社会主义新天地 提交于 2020-01-03 11:37:20

问题


It is my understanding that when a variable whose type implements Drop goes out of scope, a call to the fn drop(&mut self) function is inserted, and passed a newly-created mutable reference to the variable going out of scope.

However, how is that possible in cases where the variable was immutably bound, and it would be illegal to borrow it mutably? Here's an example of what I'm talking about:

fn main() {  
  let x = vec![1, 2, 3];
  let y = &mut x;
}

Which produces the following error: cannot borrow immutable local variable x as mutable as expected.

Something similar must happen when x would be getting dropped, because drop expects a mutable reference.


回答1:


The owner of a variable gets to decide the mutability when the variable binding is created, it's not intrinsic to the value itself:

fn main() {  
    let x = vec![1, 2, 3];
    let mut z = x;
    let y = &mut z;
}

You can think of dropping as happening when the last programmer-named variable binding gives up the ownership of the variable. The magical Drop-fairy takes ownership of your now-unneeded variable, and uses a mutable binding. Then the Drop-fairy can call Drop::drop before doing the final magic to free up the space taken by the item itself.

Note the Drop-fairy is not a real Rust concept yet. That RFC is still in a very preliminary stage.



来源:https://stackoverflow.com/questions/31597416/how-is-a-destructor-call-fn-dropmut-self-call-inserted-when-the-owning-vari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!