学习rust(五)内存管理和安全性

内存管理和安全性

程序和内存

文本段,数据段,堆栈段,堆片段

程序如何使用内存

内存管理及其分类

手动,自动,半自动

内存分配简介

堆栈

内存管理的缺陷

内存安全性

各种bug,内存泄漏

内存安全3原则

所有权

  1. let创建变量,变量成为资源的所有者,并有使用权
  2. 当变量赋值给另外一个变量时,所有权发送转移
  3. 值和变量在其作用域的末尾被清理,释放

移动和复制语义

copy特性

clone特性

闭包中的所有权 move||

借用 &, &mut

  1. 一个引用的生命周期,不能超过其被引用的时间
  2. 如果存在一个值的可变借用,那么不允许其他引用
  3. 不存在可变借用,可以出现任意数量的不可变借用

&self, &mut self ,self

生命周期

  1. 输入型生命周期
  2. 输出型生命周
'a

struct xx<'a, T>{
part: &'a T
}

生命周期的使用

  1. 函数签名
  2. 结构体和结构体字段
  3. impl代码块
  4. 生命周期子类型
  5. 在泛型上声明生命周期区间

rust中的指针类型

引用 &T &mut T

原始指针

  1. *const T
  2. *mut T

智能指针

  1. drop析构函数

Deref制度和DerefMut

智能指针

  1. Box 保存值
  2. Re引用计数
  3. Arc安全的引用计数
  4. Cell copy特征的内部可变性
  5. RefCell不需要copy特征的内部可变性
use std::rc::Rc;
use std::cell::Cell;
use std::cell::RefCell;

fn main() {
    println!("Hello, world!");

    //1  struct
    let foo1 = Foo(1023);
    let bar = &foo1;
    println!("foo1:{:?}", foo1);

    //2 life time
    let a = 10;
    let mut num = Number{num:&a};
    num.set_num(&111);
    println!("{:?}", num.get_num());


    //3
    let c1 = Cc{num:12};

    //box
    let box_one = Box::new( Cc{num:22});
    let box_one2 = *box_one;
    box_ref(box_one2);

    //rc
    let rc1 = Rc::new(Cc{num:23});
    let rc2 = rc1.clone();
    println!("rc2 {:?}", *rc2);
    println!("rc2 {:?}", Rc::strong_count(&rc2));

    //cell
    let cell1 = Cell::new( Cc2{num:Box::new(22)});
    let hand1 = & cell1;
    let hand2 = & cell1;
    hand1.set( Cc2{num:Box::new(33)});
    hand2.set( Cc2{num:Box::new(55)});
    //println!("rc2 {:?}", cell1.get());


    //ref cell
    let ref_cell1 = RefCell::new( Cc2{num:Box::new(22)});
    let hand1 = & ref_cell1;
    let hand2 = & ref_cell1;
    *hand1.borrow_mut() = Cc2{num:Box::new(33)};
    *hand2.borrow_mut() = Cc2{num:Box::new(55)};
    let borrow = hand1.borrow();
    println!("borrow:{:?}", borrow);


}

fn box_ref<T>(b: T) -> Box<T>{
    let a = b;
    Box::new(a)
}


#[derive(Debug)]
struct Foo(u32);

struct Number<'a>{
    num:&'a u8
}



impl<'a> Number<'a>{
    fn get_num(&self)->&'a u8{
        self.num
    }

    fn set_num(&mut self, new_number: &'a u8){
        self.num = new_number
    }
}

#[derive(Debug)]
struct Cc{
    num: u8
}

impl Clone for Cc {
    fn clone(&self) -> Self {
        Cc{num:self.num}
    }
}


impl Drop for Cc{
    fn drop(&mut self){
        println!("went way {:?}",self.num );
    }
}


#[derive(Debug)]
struct Cc2{
    num: Box<u32>
}
原文地址:https://www.cnblogs.com/beckbi/p/14698137.html