我目前正在学习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
Run Code Online (Sandbox Code Playgroud)
每个人都很高兴,但请想象我们是否有这样的代码:
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.
Run Code Online (Sandbox Code Playgroud)
堆分配的数组(首先分配的数组)会发生什么情况,它会一直存在到函数结束时,还是会在重新分配时被丢弃?我仍在学习Rust,因此我对内存管理的理解可能不完整。
这个问题与何时为不再拥有的资源回收存储设备中的问题有些不同。,因为这是所有者变量仍在范围内,而只是被分配了另一个值的情况。
每当将新值分配给实现类型的变量时Drop,都会在分配新值之前删除旧值。对于拥有像堆这样分配的内存的类型Box,这意味着该内存将在分配时释放。
尽管有可能在安全的Rust代码中泄漏无法访问的内存,但不太可能偶然发生。
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |