gpt4 book ai didi

rust - 在重新分配拥有该值所有权的变量后,堆分配的值会发生什么变化?

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

<分区>

我目前正在学习 Rust 编程语言,在阅读了所有权和生命周期概念(我发现它是 GC 的优雅替代品)之后,我找不到以下问题的答案。就所有权和生命周期而言,以下代码按照注释中的描述工作。

fn main() {
let mut x: u32 = 10; // x is pointing to memory in stack
println!("before reassignment: x = {}", x); // prints 10
x = 11; // memory in stack simply has been updated with another value
println!("after reassignment: x = {}", x); // prints 11
} // x is dropped here

大家都很高兴,但想象一下如果我们有这样的代码:

fn main() {
let mut x = Box::new([99; 1000]); // x owns a Box, which owns heap allocated array
println!("before reassignment: x[0] = {}", x[0]);
x = Box::new([100; 1000]); // x has been assigned another Box
// what happened to previous heap allocated array, has it been
// dropped behind the scenes, or is that a memory leak?
println!("after reassignment: x[0] = {}", x[0]);
} // x is dropped here, only the last assigned value gets dropped with it.

堆分配数组(第一个分配的那个)会发生什么,它会一直存在到函数结束,还是会在重新分配时被丢弃?我还在学习 Rust,所以我对内存管理的理解可能还不完整。

这个问题与 When is the storage reclaimed for a resource that is no longer owned? 中提出的问题略有不同,因为这是关于所有者变量仍在范围内,但只是被分配了另一个值的情况。

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