gpt4 book ai didi

rust - Rust 中的堆栈分配与堆分配究竟如何工作?

转载 作者:行者123 更新时间:2023-11-29 08:13:04 25 4
gpt4 key购买 nike

所以我理解这是如何工作的简单答案是本地的东西发生在堆栈中,盒子的东西发生在堆上。

但是,当您有更复杂的行为时会发生什么?

具体来说,让我们谈谈在 FFI 中保存不确定时间的数据,然后必须稍后从 *mut c_void 中恢复数据。

如果您“忘记”一个指针,使用 std::mem::forget 或 std::mem::transmute() 一个指向 *const 指针的指针,结果有多持久?

如果(例如)这是在函数内部完成的,然后函数返回,堆栈是否被清除并且内存变得无效?

通常来说,堆分配的“Box”指针在被销毁之前是否有效(例如,使用 read())?

我在 IRC 上被告知,这通常是正确的做法:

unsafe fn fp(v:Box<Foo>) -> *const c_void {
return transmute(foo);
}

但是,查看 libcore::raw::Box,Box 与 *const T 完全不同;真的可以吗?

最佳答案

If you 'forget' a pointer, using std::mem::forget, or std::mem::transmute() a pointer to a *const pointer how durable is the result?

如果你投了一个Box通过 fp 转化函数,指针将保持有效,只要你愿意,因为transmute正在消耗该值,因此释放内存的析构函数不会运行。 (至少,在您将其转换回 Box<...> 以让析构函数运行并释放内存之前,它是有效的。)

forget没有返回值,它只是丢弃值而不运行析构函数。

但是请注意,转换为 *const c_void需要额外的照顾,例如Foo Box<Foo>可能包含线程本地数据或引用,因此可能无法在线程之间传递或永远存在。 (这意味着指针本身永远存在/可以随心所欲地使用,但它指向的数据可能不会。)

如果你开始类型转换 &指针,您需要非常小心地处理生命周期,不要让它们脱离它们指向的数据范围(例如,您不能从函数返回指向局部变量的指针)。

If (for example) this is done inside a function and then the function returns, does the stack get cleared and the memory become invalid?

堆栈不会被“清除”(即它没有明确清零),但是使用任何指向不再存在的堆栈帧的指针是无效的。

Are 'Box' pointers which are heap allocated generally speaking valid until they get destroyed (eg. using read())?

你需要更具体,ptr::read不能在 Box 上调用直接调用ptr::read*const c_void 上肯定不会做任何有用的事情。

However, looking at libcore::raw::Box, Box isn't remotely the same as a *const T; is that really ok?

raw::Box根本不是正常的 Box 的代表. raw::Box是旧@的代表(现在 Gc )类型。 Box<T>literally a wrapper around a *mut T .

关于rust - Rust 中的堆栈分配与堆分配究竟如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25323634/

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