rust - 了解 Rust 堆栈分配

标签 rust

根据https://doc.rust-lang.org/stable/rust-by-example/std/box.html ,

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.



所以如果我有一个 std::vec::Vec<MyStruct>我添加了很多结构,这是否意味着结构是堆栈分配的?这怎么可能?如果它们在堆上,我只能拥有一组东西。堆栈上的东西是在编译时完成的,因为我明白。

最佳答案

Box 是在堆上分配的一种方式,但不是唯一的方式。其他数据结构,包括 Vec,将它们的数据存储在堆上。所以在本例中,当您创建 MyStruct 的每个实例时最初它会在堆栈上,但是一旦你把它推到 Vec 上,它就会被移动到堆中。至少,它在概念上是这样工作的;根据具体情况和编译器优化设置,Rust 可能能够避免物理写入堆栈,而是直接写入堆。

关于rust - 了解 Rust 堆栈分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62369154/

相关文章:

rust - 为什么 Read::read 和 Read::read_exact 需要初始化传递给它们的缓冲区?

compiler-construction - 写语法扩展时,是否可以查询注解类型以外的类型信息?

rust - 如何指定依赖项的确切版本?

rust - 获取一周的开始/结束日期

error-handling - 传播不同错误类型的函数的结果类型的正确错误部分是什么?

rust - 如何编写一个简单的返回json或html的扭曲处理程序?

rust - 为什么在需要&Vec <&'a str>的地方使用nomicon布局章节&Vec <&'static str> couldn'?

rust - 如何在循环中更新可变引用?

rust - Rust 时间线和所有权问题

rust - Into<PathBuf> 的多个泛型