简体   繁体   中英

Rust language - Drop & Borrow checker

fn testing(myptr :&mut Box<i32>) {
    println!("Fn is called: {}",myptr);
    *myptr=Box::new(300);
    println!("Inside: {}",myptr);
    *myptr=Box::new(0);
    println!("Inside: {}",myptr);
    drop(myptr);
}

fn main() {
    let mut myptr = Box::new(100);
    println!("Before Func: {}",myptr);
    testing(&mut myptr);
    println!("From Main: {}",myptr);
}

output

Before Func: 100
Fn is called: 100
Inside: 300
Inside: 0
From Main: 0

since i have invoked drop function i am expecting the value shouldn't be accessible even from main function but thats not happing. not able to understand why. Need help in understanding who is owning ownership and why drop function is not working.

The call to drop(myptr) in this context does not drop the Box<i32> it only drops the reference , which is effectively a no-op. You cannot drop something via a reference since it doesn't own the value. And what would the "From Main:" line print?

If you want myptr to be dropped by testing() , then you will have to take ownership of it:

fn testing(myptr: Box<i32>) {
    // myptr will be destroyed at the end of the scope
}

fn main() {
    let myptr = Box::new(100);
    testing(myptr);

    // attempting to use it afterwards will yield a compiler error
    // println!("From Main: {}", myptr);
}

If you want testing() to "nullify" myptr , use an Option :

fn testing(myptr: &mut Option<Box<i32>>) {
    *myptr = None;
}

fn main() {
    let mut myptr = Some(Box::new(100));
    println!("Before Func: {:?}", myptr); // prints "Some(100)"
    testing(&mut myptr);
    println!("From Main: {:?}", myptr); // prints "None"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM