How to allocate structs on the heap without taking up space on the stack in stable Rust?

前端 未结 4 467
北荒
北荒 2020-12-19 07:45

In this code...

struct Test { a: i32, b: i64 }
    
fn foo() -> Box {              // Stack frame:
            


        
4条回答
  •  盖世英雄少女心
    2020-12-19 08:11

    As of Rust 1.39, there seems to be only one way in stable to allocate memory on the heap directly - by using std::alloc::alloc (note that the docs state that it is expected to be deprecated). It's reasonably unsafe.

    Example:

    #[derive(Debug)]
    struct Test {
        a: i64,
        b: &'static str,
    }
    
    fn main() {
        use std::alloc::{alloc, dealloc, Layout};
    
        unsafe {
            let layout = Layout::new::();
            let ptr = alloc(layout) as *mut Test;
    
            (*ptr).a = 42;
            (*ptr).b = "testing";
    
            let bx = Box::from_raw(ptr);
    
            println!("{:?}", bx);
        }
    }
    

    This approach is used in the unstable method Box::new_uninit.

    It turns out there's even a crate for avoiding memcpy calls (among other things): copyless. This crate also uses an approach based on this.

提交回复
热议问题