gpt4 book ai didi

rust - 是否调用析构函数重新分配可变变量?

转载 作者:行者123 更新时间:2023-11-29 08:13:33 25 4
gpt4 key购买 nike

假设我已经定义了一个可变变量,它可能是一些复杂的结构,包含向量或其他具有 Drop 特性的动态分配数据。在重新分配该变量时,是否会在重新分配后立即调用析构函数?

let mut x = some_complex_struct;
while some_condition {
// ...
x = new_complex_struct;
// ...
}

我的解释是 x 获得了 new_complex_struct 的所有权,它之前拥有的值变成了无主,因此它的析构函数将在重新分配后立即被调用。我的解释正确吗?

最佳答案

My interpretation is x gains ownership on new_complex_struct, its previously owned value becomes unowned, so its destructor would be called right after reassignment. Is my interpretation correct?

是的。 This can easily be checked:

struct Foo;

impl Drop for Foo {
fn drop(&mut self) {
println!("Foo::drop");
}
}

fn main() {
let mut f = Foo;

for i in 0..5 {
println!("Before {}", i);
f = Foo;
println!("After {}", i);
}
}

将按预期打印:

Before 0
Foo::drop
After 0
Before 1
Foo::drop
After 1
Before 2
Foo::drop
After 2
Before 3
Foo::drop
After 3
Before 4
Foo::drop
After 4
Foo::drop

Rust 中的析构函数是确定性的,因此这种行为是一成不变的。

关于rust - 是否调用析构函数重新分配可变变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56308961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com