Is it possible in Rust to delete an object before

2020-02-10 05:25发布

From what I understand, the compiler automatically generates code to call the destructor to delete an object when it's no longer needed, at the end of scope.

In some situations, it is beneficial to delete an object as soon as it's no longer needed, instead of waiting for it to go out of scope. Is it possible to call the destructor of an object explicitly in Rust?

标签: rust
2条回答
何必那么认真
2楼-- · 2020-02-10 06:08

Is it possible in Rust to delete an object before the end of scope?

Yes.

Is it possible to call the destructor of an object explicitly in Rust?

No.

To clarify, you can use std::mem::drop to transfer ownership of a variable, which causes it to go out of scope:

struct Noisy;

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

fn main() {
    let a = Noisy;
    let b = Noisy;

    println!("1");

    drop(b);

    println!("2");
}
1
Dropping Noisy!
2
Dropping Noisy!

However, you are forbidden from calling the destructor (the implementation of the Drop trait) yourself. Doing so would lead to double free situations as the compiler will still insert the automatic call to the the Drop trait.


Amusing side note — the implementation of drop is quite elegant:

pub fn drop<T>(_x: T) { }
查看更多
贼婆χ
3楼-- · 2020-02-10 06:12

The official answer is to call mem::drop:

fn do_the_thing() {
    let s = "Hello, World".to_string();
    println!("{}", s);

    drop(s);

    println!("{}", 3);
}

However, note that mem::drop is nothing special. Here is the definition in full:

pub fn drop<T>(_x: T) { }

That's all.

Any function taking ownership of a parameter will cause this parameter to be dropped at the end of said function. From the point of view of the caller, it's an early drop :)

查看更多
登录 后发表回答