[Rust Basics] Rust Box Smart Pointer

preface

In Rust, Boxa smart pointer type that allocates memory on the heap and manages its lifetime. BoxProvides heap allocation and is responsible for freeing memory when ownership is transferred. BoxThis blog will introduce in detail the use of smart pointers and related concepts in Rust .

Definition and properties of Box smart pointers

Boxis a pointer to a value allocated on the heap. It provides functions for transferring ownership and freeing memory. Using Boxsmart pointers, memory safety can be guaranteed at compile time, avoiding problems such as dangling pointers and memory leaks.

BoxThe properties are as follows:

  • Store pointers on the stack, pointing to data on the heap.
  • Responsible for freeing memory on the heap when transferring ownership.
  • Fixed size, for types of known size.
  • There can only be one owner and references cannot be shared.

Create and use Box smart pointers

To create a Boxsmart pointer, we can use Box::newthe function to wrap the value in Boxa . Here's an example that demonstrates how to create and use Boxa smart pointer:

fn main() {
    
    
    let x = Box::new(5); // 创建一个 `Box` 指向整数 5
    println!("x = {}", x);
}

In the above example, we used Box::newthe function to create a pointer to the integer 5 Box. Since Boxis a smart pointer, it will automatically free the memory when the scope ends.

Through *the operator, we can Boxdereference to get the internal value. For example, *xyou can get Boxthe integer value in .

Box smart pointers and ownership transfers

BoxOne of the main roles of smart pointers is to support transfer of ownership. By wrapping the value in Boxa , we can transfer ownership from one scope to another without worrying about freeing memory.

Here's an example that demonstrates how to Boximplement ownership transfer with :

fn process_box(b: Box<i32>) {
    
    
    println!("Processing: {}", *b);
    // `Box` 的所有权在函数内部被转移,函数结束后释放内存
}

fn main() {
    
    
    let x = Box::new(5);
    process_box(x); // 所有权转移到函数内部
    // `x` 在这里已经无效,因为所有权已经转移
}

In the above example, we defined a process_boxfunction that takes a Box<i32>parameter of type . By passing Box, we transfer the ownership to the inside of the function, and the memory will be freed automatically after the function ends.

Box smart pointers and recursive types

In Rust, a recursive type is a type whose size cannot be determined at compile time. For example, structures such as linked lists and trees are types of recursion. Due to the indeterminate size of recursive types, memory cannot be allocated directly on the stack.

In this case, we can use Boxsmart pointers to solve the problem. By wrapping a node of recursive type in Boxa , we can place it on the heap and access it via a pointer.

Here's an example that demonstrates how to use Boxto solve a recursive type of problem:

enum List {
    
    
    Cons(i32, Box<List>),
    Nil,
}

use List::{
    
    Cons, Nil};

fn main() {
    
    
    let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
    // 使用 `Box` 解决递归类型
}

In the above example, we defined a recursive type Listrepresenting a linked list of integers. By using Box, we can Conswrap a pointer to the next node in a variant Box<List>.

Summarize

This blog introduces in detail Boxthe usage and features of smart pointers in Rust. BoxProvides the functions of heap allocation and ownership transfer, which can ensure memory safety at compile time and solve the problem of recursive types.

BoxI hope this blog helps you understand and apply smart pointers in Rust . Thanks for reading!

Supongo que te gusta

Origin blog.csdn.net/qq_21484461/article/details/131731732
Recomendado
Clasificación