且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rust是否会释放被覆盖变量的内存?

更新时间:2022-01-02 03:05:14

Rust没有垃圾收集器 .

Rust是否释放了被覆盖的变量的内存?

Does Rust free up the memory of overwritten variables?

是的,否则将导致内存泄漏,这将是一个非常糟糕的设计决策.重新分配变量后,内存将释放:

Yes, otherwise it'd be a memory leak, which would be a pretty terrible design decision. The memory is freed when the variable is reassigned:

struct Noisy;
impl Drop for Noisy {
    fn drop(&mut self) {
        eprintln!("Dropped")
    }
}

fn main() {
    eprintln!("0");
    let mut thing = Noisy;
    eprintln!("1");
    thing = Noisy;
    eprintln!("2");
}

0
1
Dropped
2
Dropped

第一次打招呼会发生什么

what happens with the first hello

阴影.

该变量引用的数据没有任何特殊"发生,除了您无法再访问它之外.当变量超出范围时,仍将其删除:

Nothing "special" happens to the data referenced by the variable, other than the fact that you can no longer access it. It is still dropped when the variable goes out of scope:

struct Noisy;
impl Drop for Noisy {
    fn drop(&mut self) {
        eprintln!("Dropped")
    }
}

fn main() {
    eprintln!("0");
    let thing = Noisy;
    eprintln!("1");
    let thing = Noisy;
    eprintln!("2");
}

0
1
2
Dropped
Dropped

另请参阅:

我知道将两个变量命名为相同名称会很困难

I know it would be bad to name two variables the same

这不是不好",这是设计决定.我会说使用这样的阴影是个坏主意:

It's not "bad", it's a design decision. I would say that using shadowing like this is a bad idea:

let x = "Anna";
println!("User's name is {}", x);
let x = 42;
println!("The tax rate is {}", x);

使用这样的阴影对我来说是合理的:

Using shadowing like this is reasonable to me:

let name = String::from("  Vivian ");
let name = name.trim();
println!("User's name is {}", name);

另请参阅:

但是如果这是偶然发生的,因为我在它下面声明了100行,那可能会很痛苦.

but if this happens by accident because I declare it 100 lines below it could be a real pain.

没有太大的功能以至于您偶然地"做某事.这适用于任何编程语言.

Don't have functions that are so big that you "accidentally" do something. That's applicable in any programming language.

是否可以手动清除内存?

Is there a way of cleaning memory manually?

您可以致电 drop :>

eprintln!("0");
let thing = Noisy;
drop(thing);
eprintln!("1");
let thing = Noisy;
eprintln!("2");

0
Dropped
1
2
Dropped

但是,如 oli_obk-ker指出,直到函数退出,才释放变量占用的堆栈内存,仅释放变量占用的资源.

However, as oli_obk - ker points out, the stack memory taken by the variable will not be freed until the function exits, only the resources taken by the variable.

drop的所有讨论都要求显示其(非常复杂的)实现:

All discussions of drop require showing its (very complicated) implementation:

fn drop<T>(_: T) {}

如果我在其他函数之外的全局范围内声明变量,该怎么办?

What if I declare the variable in a global scope outside of the other functions?

即使您可以创建全局变量,也永远不会释放它们.

Global variables are never freed, if you can even create them to start with.