Function understand_copy

Source
pub fn understand_copy()
Expand description

§Rust 语义:Move 语义 与 Copy 语义

  • 理解 按位复制
#[derive(Copy, Clone)]
struct A(i8, i32);
fn main() {
    let a = A(1, 2);
    let b = a; // 按位复制,复制后,b和a完全相同,包括内存对齐填充的padding部分。
    let c = A(a.0, a.1); // 逐成员复制,非按位复制,c和a的padding部分不一定相同。
}

示例二:

#[derive(Debug, Copy, Clone)]
struct A {
    a: u16,
    b: u8,
    c: bool,
}

fn main() {
    let a = unsound_a();
    // 尝试将 Some(a) 改为 a
    let some_a = Some(a);

    println!("a: {:#?}", a);
    println!("some_a: {:#?}", some_a);
}


fn unsound_a() -> A {
    #[derive(Debug, Copy, Clone)]
    struct B {
        a: u16,
        b: u8,
        c: u8,
    }
    // 依次修改 c 的值为 0,1,2 打印输出结果
    let b = B { a: 1, b: 1, c: 1 };
    unsafe {*(&b as *const B as *const A) }
}

示例三:

#![allow(unused_variables)]

use std::{ptr, mem};

fn main() {
    let mut d = String::from("cccc");
    let d_len = d.len();
    // {
        let mut c = String::with_capacity(d_len);

        unsafe {
            ptr::copy(&d, &mut c, 1);
        };
        println!("{:?}", c.as_ptr());
        // unsafe {
        //     ptr::drop_in_place(c.as_mut_ptr());
        // }
        // 注掉 drop,会产生double free,
        // 但是不注掉 drop,会产生无效指针
        mem::drop(c);
    // }

    println!("{:?}", d.as_ptr());
    d.push_str("c");
    println!("{}", d);
}

示例四: Copy 不一定只在栈上进行

use std::cell::RefCell;

fn main() {
    let a = Box::new(RefCell::new(1));
    let b = Box::new(RefCell::new(2));
    *b.borrow_mut() = *a.borrow();
    println!("b = {}", b.borrow());
}