当所有权从盒子中转移出来时,内存中会发生什么?

问题描述 投票:3回答:2

s中的变量print_struct是否引用堆或堆栈上的数据?

struct Structure {
    x: f64,
    y: u32,
    /* Use a box, so that Structure isn't copy */
    z: Box<char>,
}

fn main() {
    let my_struct_boxed = Box::new(Structure {
        x: 2.0,
        y: 325,
        z: Box::new('b'),
    });
    let my_struct_unboxed = *my_struct_boxed;
    print_struct(my_struct_unboxed);
}

fn print_struct(s: Structure) {
    println!("{} {} {}", s.x, s.y, s.z);
}

据我所知,let my_struct_unboxed = *my_struct_boxed;将所有权从包装箱转移到my_struct_unboxed,然后在功能s中转移到print_struct

实际数据会怎样?最初,它是通过调用Box::new(...)从堆栈复制到堆的,但是数据在某些时候是moved还是复制回堆栈的?如果是这样,怎么办?何时调用drops超出范围时?

rust heap-memory ownership
2个回答
1
投票

Structure中的my_struct_boxed数据存在于堆中,而Structure中的my_struct_unboxed数据存在于堆栈中。


1
投票

如果是,如何?

© www.soinside.com 2019 - 2024. All rights reserved.