Rust RAII 所有權 引用

2021-10-25 08:24:49 字數 2797 閱讀 1239

raii源自於現代c++,rust 強制實行 raii(resource acquisition is initiallization,資源獲取即初始化),所以任何物件在離開作用域時,它的析構函式(destructor)就被呼叫,然後它占有的資源就被釋放。

這種行為避免了資源洩漏(resource leak),所以你再也不用手動釋放記憶體或者擔心記憶體洩漏(memory leak)!

小示例:

fn main()

//`_box3`在這裡被銷毀,記憶體得到釋放

}

rust 中的析構函式概念是通過droptrait 提供的。當資源離開作用域,就呼叫析構函式。

你無需為每種型別都實現droptrait,只要為那些需要自己的析構函式邏輯的型別實現就可以了。

#[

derive

(debug)

]struct todrop

impl drop for todrop

}fn main()

; println!

("hello, world!=="

,to_drop);}

// hello, world!==todrop

// droping!

這裡主要是涉及在堆中申請的內容,為了極致的效能,指向堆中物件的指標,在進行多次繫結時會涉及到所有權和移動。但是我們也可以對指向堆中物件進行複製,不過這需要實現clone trait。

fn destroy_box

(c:box)"

,c);

}fn main()

, and y is {}"

, x, y)

;// rust 對基礎資料型別實現了copy,故不存在資源移動

let a = box::

new(

255u8)

; println!

("a contains {},"

,a);

let b = a;

println!

("b contains {}"

,b);

destroy_box

(b);

// println!("a contains {}", a) // 報錯!`a`不能訪問資料

// println!("b contains: {}", b); // 報錯!`b`不能訪問資料

}

當所有權轉移時,資料的可變性可能發生改變。

fn drop_box

(box_i32:box

)!!!"

,box_i32);}

fn borrow_box

(borrow_i32:

&i32)

",borrow_i32)

}fn main()

",box1)

; println!

("box2 contains is {}"

,box2)

; let box_i32 = box::

new(

100i32)

; let stack_i32 =

100i32;

borrow_box

(&box_i32)

;borrow_box

(&stack_i32)

;drop_box

(box_i32);}

// box1 contains is 100

// box2 contains is 255

// only print value is 100

// only print value is 100

// droping box contain 100!!!

可變資料可以使用&mut t進行可變借用。這叫做可變引用(mutable reference),它使

借用者可以讀/寫資料。相反,&t通過不可變引用(immutable reference)來借用資料,

借用者可以讀資料而不能更改資料。

#[

derive

(clone, copy)

]struct book

fn borrow_book

(book:

&book)

title =>{} year =>{}"

, book.author, book.title,book.year);}

fn new_edition

(book:

&mut book)

title =>{} year =>{}"

, book.author, book.title,book.year);}

fn main()

; let mut mut_book = immut_book;

//建立乙個`immutabook`的可變拷貝 #[derive(clone, copy)]

borrow_book

(&immut_book)

;//不可變地借用乙個不可變物件

borrow_book

(&mut_book)

;//不可變地借用乙個可變物件

new_edition

(&mut mut_book)

;//可變地借用乙個可變物件

}

如上,禁止可變地借用乙個不可變物件,若這樣寫會編譯報錯。

賬號所有權

關於區塊鏈 三 賬戶的所有權 傳統銀行系統 銀行卡 密碼 開戶時會記錄個人的資訊用於該賬號的所有權 位元幣系統 密碼 私鑰 私鑰 shshhfihduhdihfihsihfihdihw8ihidhhfieuiu2i374 hash hash fun shshhfihduhdihfihsihfihdi...

賬戶所有權問題

誰能用 2a38cba2390fde 位址支付,誰就擁有這個賬戶的所有權 私鑰 sdhgkdnhgggsdjuufjlkkhsuhfggdngbf hash hash fun sdhgkdnhgggsdjuufjlkkhsuhfggdngbf 2a38cba2390fde 位元幣中乙個位址對應乙個私...

std move轉換所有權

在c 11中,標準庫在中提供了乙個有用的函式std move,std move並不能移動任何東西,它唯一的功能是將乙個左值強制轉化為右值引用,繼而可以通過右值引用使用該值,以用於移動語義。從實現上講,std move基本等同於乙個型別轉換 static cast lvalue 作用是 轉換所有權,注...