调用函数返回但未分配的值的所有权会发生什么情况?



考虑以下 Rust 代码,根据 The Book 中的示例略有修改。

我试图了解在第二次运行函数dangle()main()函数中的值会发生什么(请参阅评论(。我会想象,因为该值没有分配给任何所有者,所以它会被解除分配,但到目前为止,我还没有找到信息来确认这一点。否则,我会认为反复调用dangle()会不断分配更多内存而不解除分配它。是哪个?

fn main() {
// Ownership of dangle()'s return value is passed to the variable `thingamabob`.
let thingamabob = dangle();
// No ownership specified. Is the return value deallocated here?
dangle();
println!("Ref: {}", thingamabob);
}
fn dangle() -> String {
// Ownership specified.
let s = String::from("hello");
// Ownership is passed to calling function.
s
}

当一个值没有所有者(未绑定到变量(时,它将超出范围。超出范围的值将被删除。删除值将释放与该值关联的资源。

任何不足都会导致内存泄漏,这在编程语言中是一个糟糕的主意。

另请参阅:

  • 在 Rust 中是否可以在范围结束之前删除对象?
  • Rust 如何知道是否在堆栈展开期间运行析构函数?
  • Rust 会释放覆盖变量的内存吗?

在您的示例中,第二次调用创建一个未命名的临时值,其生存期在该代码行之后立即结束,因此它会立即超出范围(并且回收任何资源(。

如果使用let将值绑定到名称,则其生存期将一直持续到当前词法作用域结束(右大括号(。

您可以通过在简单类型上实现Drop特征来查看其生存期何时结束,从而自己探索其中的一些内容。这是我为玩这个(游乐场(而制作的一个小程序:

#[derive(Debug)]
struct Thing {
val: i32,
}
impl Thing {
fn new(val: i32) -> Self {
println!("Creating Thing #{}", val);
Thing { val }
}
fn foo(self, val: i32) -> Self {
Thing::new(val)
}
}
impl Drop for Thing {
fn drop(&mut self) {
println!("Dropping {:?}", self);
}
}
pub fn main() {
let _t1 = Thing::new(1);
Thing::new(2); // dropped immediately
{
let t3 = Thing::new(3);
Thing::new(4).foo(5).foo(6); // all are dropped, in order, as the next one is created
println!("Doing something with t3: {:?}", t3);
} // t3 is dropped here
} // _t1 is dropped last

相关内容

最新更新