如何在稳定的 Rust 中在不占用堆栈空间的情况下在堆上分配结构? [英] How to allocate structs on the heap without taking up space on the stack in stable Rust?

查看:50
本文介绍了如何在稳定的 Rust 中在不占用堆栈空间的情况下在堆上分配结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中...

struct Test { a: i32, b: i64 }
    
fn foo() -> Box<Test> {              // Stack frame:
    let v = Test { a: 123, b: 456 }; // 12 bytes
    Box::new(v)                      // `usize` bytes (`*const T` in `Box`)
}

...据我所知(忽略可能的优化),v 在堆栈上分配,然后复制到堆中,然后在 Box 中返回.

... as far as I understand (ignoring possible optimizations), v gets allocated on the stack and then copied to the heap, before being returned in a Box.

这个代码...

fn foo() -> Box<Test> {
    Box::new(Test { a: 123, b: 456 })
}

...应该没有什么不同,大概是因为应该有一个用于结构分配的临时变量(假设编译器对 Box::new()<中的实例化表达式没有任何特殊语义/code>).

...shouldn't be any different, presumably, since there should be a temporary variable for struct allocation (assuming compiler doesn't have any special semantics for the instantiation expression inside Box::new()).

我发现 返回位置的值是否总是在父堆栈帧或接收框中分配?.关于我的具体问题,它只提出了实验性的 box 语法,但主要讨论了编译器优化(复制省略).

I've found Do values in return position always get allocated in the parents stack frame or receiving Box?. Regarding my specific question, it only proposes the experimental box syntax, but mostly talks about compiler optimizations (copy elision).

所以我的问题仍然存在:使用 stable Rust,如何在不依赖编译器优化的情况下直接在堆上分配 struct ?

So my question remains: using stable Rust, how does one allocate structs directly on the heap, without relying on compiler optimizations?

推荐答案

从 Rust 1.39 开始,似乎只有一种稳定的方法可以直接在堆上分配内存 - 使用 std::alloc::alloc(注意文档声明它预计将被弃用).这是相当不安全的.

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.

示例:

#[derive(Debug)]
struct Test {
    a: i64,
    b: &'static str,
}

fn main() {
    use std::alloc::{alloc, dealloc, Layout};

    unsafe {
        let layout = Layout::new::<Test>();
        let ptr = alloc(layout) as *mut Test;

        (*ptr).a = 42;
        (*ptr).b = "testing";

        let bx = Box::from_raw(ptr);

        println!("{:?}", bx);
    }
}

这种方法用在不稳定的方法中Box::new_uninit.

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

事实证明,甚至还有一个箱子可以避免 memcpy 调用(除其他外):无副本.这个 crate 也使用了基于此的方法.

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.

这篇关于如何在稳定的 Rust 中在不占用堆栈空间的情况下在堆上分配结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆