谁拥有堆中的 Box?
Who owns a Box in the heap?
我现在正在学习 Rust。我想检查一下我对 Rust 所有权的理解。我对递归结构中的所有权和借用概念感到困惑。我在 rustbyexample.com
中看到这段代码
// Allow Cons and Nil to be referred to without namespacing
use List::{Cons, Nil};
// A linked list node, which can take on any of these two variants
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box<List>),
// Nil: A node that signifies the end of the linked list
Nil,
}
// Methods can be attached to an enum
impl List {
// Create an empty list
fn new() -> List {
// `Nil` has type `List`
Nil
}
// Consume a list, and return the same list with a new element at its front
fn prepend(self, elem: u32) -> List {
// `Cons` also has type List
Cons(elem, Box::new(self))
}
// Return the length of the list
fn len(&self) -> u32 {
// `self` has to be matched, because the behavior of this method
// depends on the variant of `self`
// `self` has type `&List`, and `*self` has type `List`, matching on a
// concrete type `T` is preferred over a match on a reference `&T`
match *self {
// Can't take ownership of the tail, because `self` is borrowed;
// instead take a reference to the tail
Cons(_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
}
}
// Return representation of the list as a (heap allocated) string
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Create an empty linked list
let mut list = List::new();
// Append some elements
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Show the final state of the list
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}
如何可视化这段代码的栈和堆?
据我了解,prepend
取得列表的所有权,在堆中分配 space 并将列表移至堆。 prepend
完成后,它将新创建的列表移动(授予所有权)到外部变量。
这个可视化是否正确?
首先 List::new return Nil 所以堆栈将包含 Nil。
在list.prepend(1)执行后,Nil会在堆中地址0x0000处(假设),栈中会包含Cons(1,0x0000)。
在list.prepend(2)执行后Cons(1,0x0000)将在堆中地址0x00002(假设),堆栈将包含Cons(2,0x0002)。
在list.prepend(3)执行后Cons(2,0x0002)将在堆中地址0x00004(假设),堆栈将包含Cons(3,0x0004)。
现在,谁拥有 Cons(1,0x0000) 的所有权? Cons(2,0x0002) 是否拥有 Cons(1,0x0000) 的所有权?堆中的变量是否允许拥有资源的所有权?
根据这段代码,我假设堆中的变量可能拥有资源的所有权,因此如果 Rust 释放该变量,它也会释放该资源。这个对吗?
Box<Foo>
表示堆上某处的 Foo
实例,由 Box
对象管理和拥有。
所以在你的列表中,最终值为:
let list = Cons(3, Box::new(Cons(2, Box::new(Cons(1, Box::new(Nil))))))
list
拥有一个 List
对象,它是枚举的 Cons
变体,拥有一个 u32
值 3
和一个 Box<List>
- 此
Box<List>
管理并拥有一个 List
实例:一个 Cons
变体拥有一个 2
值和另一个 Box<List>
- 第二个
Box<List>
管理并拥有一个 List
实例:一个 Cons
变体拥有一个 1
值和一个 Box<List>
- 最后一个
Box<List>
管理并拥有一个 List
实例:一个 Nil
变体。
所以是的,a Box
的内容可能拥有其他 Box
es,并且当 a Box
被销毁时,它会适当地销毁其内容,这是对它自己的期望也适当地销毁它的内容,直到拥有树的底部。
我现在正在学习 Rust。我想检查一下我对 Rust 所有权的理解。我对递归结构中的所有权和借用概念感到困惑。我在 rustbyexample.com
中看到这段代码// Allow Cons and Nil to be referred to without namespacing
use List::{Cons, Nil};
// A linked list node, which can take on any of these two variants
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box<List>),
// Nil: A node that signifies the end of the linked list
Nil,
}
// Methods can be attached to an enum
impl List {
// Create an empty list
fn new() -> List {
// `Nil` has type `List`
Nil
}
// Consume a list, and return the same list with a new element at its front
fn prepend(self, elem: u32) -> List {
// `Cons` also has type List
Cons(elem, Box::new(self))
}
// Return the length of the list
fn len(&self) -> u32 {
// `self` has to be matched, because the behavior of this method
// depends on the variant of `self`
// `self` has type `&List`, and `*self` has type `List`, matching on a
// concrete type `T` is preferred over a match on a reference `&T`
match *self {
// Can't take ownership of the tail, because `self` is borrowed;
// instead take a reference to the tail
Cons(_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
}
}
// Return representation of the list as a (heap allocated) string
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Create an empty linked list
let mut list = List::new();
// Append some elements
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Show the final state of the list
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}
如何可视化这段代码的栈和堆?
据我了解,prepend
取得列表的所有权,在堆中分配 space 并将列表移至堆。 prepend
完成后,它将新创建的列表移动(授予所有权)到外部变量。
这个可视化是否正确?
首先 List::new return Nil 所以堆栈将包含 Nil。
在list.prepend(1)执行后,Nil会在堆中地址0x0000处(假设),栈中会包含Cons(1,0x0000)。
在list.prepend(2)执行后Cons(1,0x0000)将在堆中地址0x00002(假设),堆栈将包含Cons(2,0x0002)。
在list.prepend(3)执行后Cons(2,0x0002)将在堆中地址0x00004(假设),堆栈将包含Cons(3,0x0004)。
现在,谁拥有 Cons(1,0x0000) 的所有权? Cons(2,0x0002) 是否拥有 Cons(1,0x0000) 的所有权?堆中的变量是否允许拥有资源的所有权?
根据这段代码,我假设堆中的变量可能拥有资源的所有权,因此如果 Rust 释放该变量,它也会释放该资源。这个对吗?
Box<Foo>
表示堆上某处的 Foo
实例,由 Box
对象管理和拥有。
所以在你的列表中,最终值为:
let list = Cons(3, Box::new(Cons(2, Box::new(Cons(1, Box::new(Nil))))))
list
拥有一个List
对象,它是枚举的Cons
变体,拥有一个u32
值3
和一个Box<List>
- 此
Box<List>
管理并拥有一个List
实例:一个Cons
变体拥有一个2
值和另一个Box<List>
- 第二个
Box<List>
管理并拥有一个List
实例:一个Cons
变体拥有一个1
值和一个Box<List>
- 最后一个
Box<List>
管理并拥有一个List
实例:一个Nil
变体。
所以是的,a Box
的内容可能拥有其他 Box
es,并且当 a Box
被销毁时,它会适当地销毁其内容,这是对它自己的期望也适当地销毁它的内容,直到拥有树的底部。