国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust- 智能指針

這篇具有很好參考價(jià)值的文章主要介紹了Rust- 智能指針。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

Smart pointers

A smart pointer is a data structure that not only acts like a pointer but provides additional functionality. This “smartness” comes from the fact that smart pointers encapsulate additional logical or semantic rules, which are automatically applied to simplify memory or resource management tasks.

While different programming languages implement smart pointers in various ways, they all share a common goal: to manage the life cycle of the resources they point to.

Here are some key features of smart pointers:

  1. Ownership: Smart pointers keep track of the memory they point to, and can automatically reclaim (or “free”) that memory when it’s no longer needed. This can greatly simplify memory management, as the programmer doesn’t need to manually release memory, reducing the risk of memory leaks.

  2. Reference Counting: Some smart pointers, like the Rc<T> in Rust or shared_ptr in C++, keep a count of the number of references (i.e., pointers) to an object. This object is only deallocated when there are no more references to it.

  3. Dereferencing: Like regular pointers, smart pointers implement the dereferencing operation, allowing access to the data they point to.

  4. Polymorphism: In object-oriented languages, smart pointers can be used to enable polymorphism when pointing to base and derived class objects.

  5. Thread Safety: Some smart pointers, like Arc<T> in Rust or std::atomic_shared_ptr in C++20, are thread-safe, meaning they can be safely used in concurrent programming.

In Rust, smart pointers are essential components due to the language’s focus on safety and zero-cost abstractions. Box<T>, Rc<T>, and RefCell<T> are some of the commonly used smart pointers in Rust.

  1. Box<T>: This is the simplest kind of smart pointer. It allows you to put data on the heap rather than the stack. Box<T> is often used in Rust in two scenarios: when you have a type of known size but need to store a value of a type that might have an unknown size at compile time, or when you have a large data item and want to transfer ownership to a function without copying the data to prevent stack overflow.

  2. Rc<T>: “Rc” stands for reference counting. The Rc<T> smart pointer allows your program to have multiple read-only references to the same data item on the heap. It keeps track of the number of references to the data on the heap, and once the reference count goes to zero, meaning there are no more references to the data, it cleans up the data.

  3. RefCell<T>: Rust performs borrow checking at compile time which ensures that references to data obey the rules of either one write or multiple reads. However, sometimes you may need to do such checking at runtime. RefCell<T> provides this functionality. This means that while you can borrow mutable references at runtime, your program will panic if you violate the rules of one write or multiple reads.

These are some of the basic smart pointers in Rust. There are several other smart pointers, like Arc<T>, Mutex<T>, etc., which are all designed to deal with ownership and concurrency issues in Rust.

It’s worth noting that while these types are called “smart pointers”, they’re not limited to mimicking pointer-like behavior. They’re actually more general constructs often used to add structure to a value, such as tracking reference counts, thread-safe access, and more.

Box< T >

Box<T> is a very important smart pointer in Rust. It allows you to store data on the heap rather than the stack. This is mainly used in Rust for the following two scenarios:

  1. Moving data to the heap: By default, Rust stores data on the stack. However, stack space is limited and the data on the stack is immediately removed when it goes out of scope. If you need to store a large amount of data in memory or need to pass data between scopes without losing ownership, you can use Box<T> to move the data to the heap.

  2. Storing dynamically sized types: In Rust, the size of all types must be known at compile time. However, there might be cases where you want to store a type whose size is not known at compile time. Box<T> can be used in this case, as the size of Box<T> itself is known regardless of the size of the data on the heap it points to.

When using Box<T>, Rust will automatically clean up the data on the heap when the Box<T> goes out of scope, meaning you do not need to manually manage memory.

Here is a simple example of Box<T>:

fn main() {
    let b = Box::new(5); // b is a pointer to a box in the heap
    println!("b = {}", b);
}

In this example, the integer 5 is stored on the heap, rather than on the stack. The variable b is a pointer to the value stored on the heap. When b goes out of scope, Rust’s automatic memory management system cleans up the data on the heap, so you do not need to manually free the memory.

use std::ops::Deref;
fn main() {
    /*
        如果一個(gè)結(jié)構(gòu)體實(shí)現(xiàn)了deref和drop的Trait,那他們就不是普通結(jié)構(gòu)體了。
        Rust提供了堆上存儲(chǔ)數(shù)據(jù)的能力并把這個(gè)能力封裝到了Box中。
        把棧上的數(shù)據(jù)搬到堆上的能力,就叫做裝箱。

        Box可以把數(shù)據(jù)存儲(chǔ)到堆上,而不是棧上,box 裝箱,棧還是包含指向堆上數(shù)據(jù)的指針。
     */
    let a = 6;
    let b = Box::new(a);
    println!("b = {}", b); // b = 6

    let price1 = 158;
    let price2 = Box::new(price1);
    println!("{}", 158 == price1);  // true
    println!("{}", 158 == *price2); // true

    let x = 666;
    let y = CustomBox::new(x);

    println!("666 == x is {}", 666 == x);   // 666 == x is true
    println!("666 == *y is {}", 666 == *y); // 666 == *y is true
    println!("x == *y is {}", x == *y);     // x == *y is true
}

struct CustomBox<T> {
    value: T
}

impl <T> CustomBox<T> {
    fn new(v: T) -> CustomBox<T> {
        CustomBox { value: v }
    }
}

impl <T> Deref for CustomBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.value
    }
}

impl <T> Drop for CustomBox<T> {
    fn drop(&mut self) {
        println!("drop CustomBox 對(duì)象!")
    }
}

Rc < T >

Rc<T> stands for ‘Reference Counting’. It’s a smart pointer that allows you to have multiple owners of the same data. When each owner goes out of scope, the reference count is decreased. When the count reaches zero, the data is cleaned up.

Here’s a simple example:

use std::rc::Rc;

fn main() {
    let data = Rc::new("Hello, World!"); // data now has a reference count of 1

    {
        let _clone = Rc::clone(&data); // data now has a reference count of 2
        println!("Inside the scope, data is: {}", *_clone);
    } // _clone goes out of scope and data's reference count decreases to 1

    println!("Outside the scope, data is: {}", *data);
} // data goes out of scope and its reference count decreases to 0, the data is cleaned up

RefCell < T >

RefCell<T> provides ‘interior mutability’, a design pattern in Rust that allows you to mutate data even when there are immutable references to that data. It enforces the borrowing rules at runtime instead of compile time.

Here’s a simple example:

use std::cell::RefCell;

fn main() {
    let data = RefCell::new(5);

    {
        let mut mutable_reference = data.borrow_mut();
        *mutable_reference += 1;
        println!("Inside the scope, data is: {}", *mutable_reference);
    } // mutable_reference goes out of scope, the lock is released

    println!("Outside the scope, data is: {}", *data.borrow());
}

In this example, you can see that we borrowed a mutable reference to the data inside RefCell using borrow_mut, modified it, and then the lock was automatically released when the mutable reference went out of scope. This demonstrates the dynamic checking that RefCell<T> provides.

Note1: The borrow_mut() function is a method of RefCell<T> in Rust. This function is used to gain mutable access to the underlying value that the RefCell wraps around.

The RefCell struct in Rust enforces the borrow rules at runtime, allowing you to have multiple immutable references or one mutable reference at any point in time. If you attempt to violate these rules, your program will panic at runtime.

When you call borrow_mut() on a RefCell, you get a RefMut smart pointer that allows mutable access to the underlying data. Once this RefMut is dropped (which happens automatically when it goes out of scope), others can then borrow the RefCell again.

Here’s an example:

use std::cell::RefCell;

fn main() {
    let data = RefCell::new(5);

    {
        let mut mutable_reference = data.borrow_mut();
        *mutable_reference += 1;
        println!("Inside the scope, data is: {}", *mutable_reference);
    } // mutable_reference goes out of scope, the lock is released

    println!("Outside the scope, data is: {}", *data.borrow());
}

In this example, mutable_reference is a mutable reference to the integer wrapped in data, which is a RefCell. We increment the integer by 1, and after mutable_reference goes out of scope, we can borrow data again.

Note2: The borrow() function is a method of RefCell<T> in Rust. This function is used to gain immutable access to the underlying value that the RefCell wraps around.

Similar to borrow_mut(), it provides a way to access the data inside the RefCell. The difference is that borrow() gives you an immutable reference (Ref<T>), while borrow_mut() gives you a mutable reference (RefMut<T>).

The RefCell checks at runtime to make sure the borrowing rules are not violated, which are:

  1. You may have either one mutable reference or any number of immutable references at the same time, but not both.
  2. References must always be valid.

If you try to call borrow() when the value is already mutably borrowed (through borrow_mut()), or try to call borrow_mut() when the value is immutably borrowed (through borrow()), your program will panic at runtime.

Here’s how you might use borrow():

use std::cell::RefCell;

fn main() {
    let data = RefCell::new(5);

    {
        let mutable_reference = data.borrow_mut();
        *mutable_reference += 1;
    } // mutable_reference goes out of scope, the lock is released

    let immutable_reference = data.borrow();
    println!("Data is: {}", *immutable_reference);
} 

In this example, we first use borrow_mut() to mutate the value inside data, then we use borrow() to get an immutable reference to the data.文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-620380.html

到了這里,關(guān)于Rust- 智能指針的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • rust學(xué)習(xí)-智能指針

    rust學(xué)習(xí)-智能指針

    示例1 無(wú)意義的例子:將一個(gè)單獨(dú)的值存放在堆上并不是很有意義,b更應(yīng)該放到棧上 示例2-遞歸類(lèi)型 一種無(wú)法在編譯時(shí)知道大小的類(lèi)型是 遞歸類(lèi)型(recursive type) 其值的一部分可以是相同類(lèi)型的另一個(gè)值 遞歸類(lèi)型來(lái)源于Lisp語(yǔ)言:cons 函數(shù)(“construct function\\\" 的縮寫(xiě))利用兩

    2024年02月16日
    瀏覽(14)
  • rust 智能指針

    Rust中基本數(shù)據(jù)類(lèi)型(如整數(shù)、浮點(diǎn)數(shù)、布爾值等)通常存儲(chǔ)在棧上。而動(dòng)態(tài)分配的數(shù)據(jù),如 BoxT 和 VecT 等,存儲(chǔ)在堆上。 Rust 中 Box 是一種智能指針類(lèi)型,通常用于將值放置在堆上而不是棧上。在 Rust 中,由于所有值的默認(rèn)生命周期都在當(dāng)前作用域結(jié)束時(shí)結(jié)束,因此在情況需

    2024年02月06日
    瀏覽(19)
  • 【跟小嘉學(xué) Rust 編程】十五、智能指針

    【跟小嘉學(xué) Rust 編程】一、Rust 編程基礎(chǔ) 【跟小嘉學(xué) Rust 編程】二、Rust 包管理工具使用 【跟小嘉學(xué) Rust 編程】三、Rust 的基本程序概念 【跟小嘉學(xué) Rust 編程】四、理解 Rust 的所有權(quán)概念 【跟小嘉學(xué) Rust 編程】五、使用結(jié)構(gòu)體關(guān)聯(lián)結(jié)構(gòu)化數(shù)據(jù) 【跟小嘉學(xué) Rust 編程】六、枚舉

    2024年02月11日
    瀏覽(23)
  • Rust編程語(yǔ)言入門(mén)之智能指針

    指針:一個(gè)變量在內(nèi)存中包含的是一個(gè)地址(指向其它數(shù)據(jù)) Rust 中最常見(jiàn)的指針就是”引用“ 引用: 使用 借用它指向的值 沒(méi)有其余開(kāi)銷(xiāo) 最常見(jiàn)的指針類(lèi)型 智能指針是這樣一些數(shù)據(jù)結(jié)構(gòu): 行為和指針相似 有額外的元數(shù)據(jù)和功能 通過(guò)記錄所有者的數(shù)量,使一份數(shù)據(jù)被多個(gè)

    2023年04月16日
    瀏覽(26)
  • 【Rust 基礎(chǔ)篇】Rust 的 `Rc<RefCell<T>>` - 共享可變性的智能指針

    在 Rust 中, RcRefCellT 是一種組合智能指針,用于實(shí)現(xiàn)多所有權(quán)共享可變數(shù)據(jù)。 Rc 允許多個(gè)所有者共享相同的數(shù)據(jù),而 RefCell 允許在有多個(gè)引用的情況下對(duì)數(shù)據(jù)進(jìn)行可變操作。 本篇博客將詳細(xì)介紹 Rust 中 RcRefCellT 的使用方法和相關(guān)概念,以及它在代碼中的應(yīng)用場(chǎng)景。 RcRefCell

    2024年02月16日
    瀏覽(30)
  • 【Rust】——通過(guò)Deref trait將智能指針當(dāng)作常規(guī)引用處理

    ??博主現(xiàn)有專(zhuān)欄: ????????????????C51單片機(jī)(STC89C516),c語(yǔ)言,c++,離散數(shù)學(xué),算法設(shè)計(jì)與分析,數(shù)據(jù)結(jié)構(gòu),Python,Java基礎(chǔ),MySQL,linux,基于HTML5的網(wǎng)頁(yè)設(shè)計(jì)及應(yīng)用,Rust(官方文檔重點(diǎn)總結(jié)),jQuery,前端vue.js,Javaweb開(kāi)發(fā),Python機(jī)器學(xué)習(xí)等 ??主頁(yè)鏈接: ????

    2024年04月26日
    瀏覽(23)
  • rust 自動(dòng)化測(cè)試、迭代器與閉包、智能指針、無(wú)畏并發(fā)

    rust 自動(dòng)化測(cè)試、迭代器與閉包、智能指針、無(wú)畏并發(fā)

    編寫(xiě)測(cè)試可以讓我們的代碼在后續(xù)迭代過(guò)程中不出現(xiàn)功能性缺陷問(wèn)題;理解迭代器、閉包的函數(shù)式編程特性; BoxT 智能指針在堆上存儲(chǔ)數(shù)據(jù), RcT 智能指針開(kāi)啟多所有權(quán)模式等;理解并發(fā),如何安全的使用線(xiàn)程,共享數(shù)據(jù)。 編寫(xiě)測(cè)試以方便我們?cè)诤罄m(xù)的迭代過(guò)程中,不會(huì)改壞

    2024年02月16日
    瀏覽(19)
  • Rust踩雷筆記(5)——刷點(diǎn)鏈表的題(涉及智能指針Box,持續(xù)更新)

    只能說(shuō)Rust鏈表題的畫(huà)風(fēng)和C++完全不一樣,作為新手一時(shí)間還不太適應(yīng),于是單獨(dú)為鏈表、智能指針開(kāi)一篇,主要記錄leetcode相關(guān)題型的答案以及注意事項(xiàng)。 ??關(guān)鍵操作 as_ref() 將 OptionT 、 OptionT 或者 mut OptionT 轉(zhuǎn)換為 OptionT as_mut() 將 OptionT 、 mut OptionT 轉(zhuǎn)換為 Optionmut T ,不能對(duì)

    2024年02月11日
    瀏覽(19)
  • Rust中的函數(shù)指針

    通過(guò)函數(shù)指針允許我們使用函數(shù)作為另一個(gè)函數(shù)的參數(shù)。函數(shù)的類(lèi)型是 fn (使用小寫(xiě)的 ”f” )以免與 Fn 閉包 trait 相混淆。fn 被稱(chēng)為 函數(shù)指針(function pointer)。指定參數(shù)為函數(shù)指針的語(yǔ)法類(lèi)似于閉包。 函數(shù)指針類(lèi)型(使用? fn ?寫(xiě)出)指向那些在編譯時(shí)不必知道函

    2024年02月02日
    瀏覽(13)
  • Rust語(yǔ)言中級(jí)教程之指針

    指針是計(jì)算機(jī)引用無(wú)法立即直接訪(fǎng)問(wèn)的數(shù)據(jù)的一種方式(類(lèi)比 書(shū)的目錄) 數(shù)據(jù)在物理內(nèi)存(RAM)中是分散的存儲(chǔ)著 地址空間是檢索系統(tǒng) 指針就被編碼為內(nèi)存地址,使用 usize 類(lèi)型的整數(shù)表示。 一個(gè)地址就會(huì)指向地址空間中的某個(gè)地方 地址空間的范圍是 OS 和 CPU 提供的外觀界

    2024年02月02日
    瀏覽(17)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包