Rust手动内存管理 [英] Rust manual memory management

查看:448
本文介绍了Rust手动内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始学习C时,我实现了常见的数据结构,例如列表,地图和树.当请求时,我使用malloccallocreallocfree来手动管理内存.我使用newdelete对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::newRc::newArc::new),如果要基于堆的数组,则只需使用VecBox<[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手动内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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