深入浅出Rust(第二部分-2)

2021-01-25  本文已影响0人  沉寂之舟

传送门:
深入浅出Rust(第一部分-1)
深入浅出Rust(第一部分-2)
深入浅出Rust(第二部分-1)
深入浅出Rust(第二部分-2)
深入浅出Rust(第三部分-1)
深入浅出Rust(第三部分-2)
深入浅出Rust(第四部分)
深入浅出Rust(第五部分)


第二部分 - 内存安全 -2

第16章 解引用

解引用(deref是)取引用(Ref)的反操作,使用"*"操作符

1. 自定义解引用

#[lang = "deref"]
#[doc(alias = "*")]
#[doc(alias = "&*")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Deref {
    /// The resulting type after dereferencing.
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_diagnostic_item = "deref_target"]
    type Target: ?Sized;

    /// Dereferences the value.
    #[must_use]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_diagnostic_item = "deref_method"]
    fn deref(&self) -> &Self::Target;
}

#[lang = "deref_mut"]
#[doc(alias = "*")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait DerefMut: Deref {
    /// Mutably dereferences the value.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn deref_mut(&mut self) -> &mut Self::Target;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for &mut T {
    fn deref_mut(&mut self) -> &mut T {
        *self
    }
}
16-1.png

2. 自动解引用

fn main(){
    let s = "hello";
    println!("length: {}", (&&&&&&&&s).len());
}

这么夸张的&,也能编译过,就是因为自动解引用进行了拆解

3. 自动解引用的用处

4. 手工处理

5. 智能指针

第17章 泄露

1. 内存泄露(构造一个内存泄露的代码)

17-1-1.png

在Rust中,编写一段内存泄露的代码并不容易...

2. 内存泄露属于内存安全

3. 析构函数泄露(没有调用到)

第18章 Panic

1. 什么是Panic

2. Panic实现机制

pannic::catch_unwind
18-1.png

3.Panic Safety

pub fn catch unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) - > Result<R> 

这个要求闭包参数满足UnWindSafe的条件.

第19章 Unsafe

1. unsafe关键字

2. 裸指针

3. 内置函数

4. 分割借用

5. 协变(??,待补)

6. 未定义行为(可能由unsafe产生)

19-1.png

第20章 Vec源码分析

上一篇 下一篇

猜你喜欢

热点阅读