rust的指针作为函数返回值是直接传递,还是先销毁后创建?

 这是我自己想到的问题,结果去知呼提问,还没等别人回答, 我自己就想到方法实验了。。

fn main() {
    let mut a = 34;
    println!("a's addr:{:p}", &a);
    let p = &mut a;
    println!("p's addr:{:p}", &p);
    println!("out test_pointer p's addr:{:p}", &test_pointer(p));

    let b = 1;
    let bp = &b;
    println!("in main bp's addr:{:p}", p);
    pointer_addr(bp);
    pointer_addr1(bp);
}

fn test_pointer(p: &mut i32) -> &mut i32 {
    *p = 32;
    println!("in test_pointer p's addr:{:p}", &p);
    p
}

fn pointer_addr(p: &i32) -> &i32 {
    println!("in pointer_addr p's addr:{:p}", p);
    p
}

fn pointer_addr1(p: &i32) -> &i32 {
    println!("in pointer_addr1 p's addr:{:p}", p);
    p
}

 结果:

cargo run
   Compiling pointer v0.1.0 (file:///home/xiaotie/code/my/learn_rust/pointer)
     Running `target/debug/pointer`
a's addr:0x7ffd05efe8fc
p's addr:0x7ffd05efe868
in test_pointer p's addr:0x7ffd05efe728
out test_pointer p's addr:0x7ffd05efe778
in pointer_addr p's addr:0x7ffc03bbd504
in pointer_addr1 p's addr:0x7ffc03bbd504

 事实证明指针在函数返回的过程中是不是销毁在创建也不是直接传递,而是在作用域外再创建一个指针,但是这个指针不会在函数结束后销毁,而是无效,但是会被复用。

你可能感兴趣的:(返回值)