gpt4 book ai didi

rust - 了解 Rust 堆栈分配

转载 作者:行者123 更新时间:2023-12-03 11:25:53 25 4
gpt4 key购买 nike

根据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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com