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

后端 未结 2 1334
遇见更好的自我
遇见更好的自我 2020-12-06 01:35

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 som

相关标签:
2条回答
  • 2020-12-06 01:48

    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 :)

    0 讨论(0)
  • 2020-12-06 01:54

    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) { }
    
    0 讨论(0)
提交回复
热议问题