Rust手动内存管理

编程入门 行业动态 更新时间:2024-10-27 06:21:54
本文介绍了Rust手动内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我开始学习C时,我实现了常见的数据结构,例如列表,地图和树.当请求时,我使用malloc,calloc,realloc和free来手动管理内存.我使用new和delete对C ++做了同样的事情.

When I began learning C, I implemented common data structures such as lists, maps and trees. I used malloc, calloc, realloc and free to manage the memory manually when requested. I did the same thing with C++, using new and delete.

现在来了Rust.至少在稳定版本中,Rust似乎没有提供与C或C ++相对应的任何函数或运算符.

Now comes Rust. It seems like Rust doesn't offer any functions or operators which correspond to the ones of C or C++, at least in the stable release.

是 Heap 结构和 ptr 模块(标记为experimental),用于此类东西吗?

Are the Heap structure and the ptr module (marked with experimental) the ones to look at for this kind of thing?

我知道这些数据结构已经在语言中了.这是为了学习.

I know that these data structures are already in the language. It's for the sake of learning.

推荐答案

直接访问Rust中的内存分配器是非常不寻常的.通常,您希望对单个对象使用智能指针构造函数(Box::new,Rc::new,Arc::new),如果要基于堆的数组,则只需使用Vec或Box<[T]>.

It's very unusual to directly access the memory allocator in Rust. You generally want to use the smart pointer constructors (Box::new, Rc::new, Arc::new) for single objects and just use Vec or Box<[T]> if you want a heap-based array.

如果您确实想分配内存并获取指向它的原始指针,则可以查看Rc的实现. (不是Box.Box是神奇的.)为了获取其后备内存,它实际上创建了Box,然后使用其into_raw_non_null函数来获取原始指针.对于销毁,它使用分配器API,但也可以使用Box::from_raw然后使用drop.

If you really want to allocate memory and get a raw pointer to it, you can look at the implementation of Rc. (Not Box. Box is magical.) To get its backing memory, it actually creates a Box and then uses its into_raw_non_null function to get the raw pointer out. For destroying, it uses the allocator API, but could alternatively use Box::from_raw and then drop that.

更多推荐

Rust手动内存管理

本文发布于:2023-10-30 03:20:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541614.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存管理   Rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!