当拥有变量不可变时,如何插入析构函数调用`fn drop(& mut self)`调用? [英] How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable?

查看:100
本文介绍了当拥有变量不可变时,如何插入析构函数调用`fn drop(& mut self)`调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当类型实现为Drop的变量超出范围时,将插入对fn drop(&mut self)函数的调用,并将新创建的可变引用传递给超出范围的变量. /p>

但是,在变量不可变地绑定并且以可变方式借用它的情况下,这怎么可能呢?这是我正在谈论的示例:

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

会产生以下错误:不能按预期借用不可变的局部变量x .

x被删除时,必须发生类似的事情,因为drop期望可变的引用.

解决方案

在创建变量绑定时,变量的所有者可以决定可变性,它不是值本身固有的: /p>

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

您可以考虑在最后一个程序员命名的变量绑定放弃该变量的所有权时发生删除.神奇的Drop-fairy拥有您现在不需要的变量的所有权,并使用可变绑定.然后,Drop-fairy可以调用Drop::drop,然后再做最后的魔术以释放物品本身占用的空间.

注意 Drop-fairy还不是真正的Rust概念. RFC仍处于非常初步的阶段.

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.

解决方案

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.

这篇关于当拥有变量不可变时,如何插入析构函数调用`fn drop(& mut self)`调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆