gpt4 book ai didi

memory-management - `String::with_capacity()` 等于 `malloc` 吗?

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

我读了this article几天前,我想在 Rust 中实现这种东西的最佳方法是什么。文章建议在每次迭代后使用缓冲区而不是打印字符串。

String::with_capacity()(或 Vec)等于 C 中的 malloc 是否正确?

代码示例:

String::with_capacity(size * 4096)

等于:

char *buf = malloc(size * 4096);

最佳答案

它不是“相等”,Rust 的 String是一个复合对象; String::with_capacity创建一个 String 这不仅是一个缓冲区;它是 Vec<u8> 的包装器:

pub struct String {
vec: Vec<u8>,
}

还有一个 Vec 不仅仅是内存中的一个部分 - 它还包含一个 RawVec及其长度:

pub struct Vec<T> {
buf: RawVec<T>,
len: usize,
}

还有一个 RawVec 也不是原始的:

pub struct RawVec<T> {
ptr: Unique<T>,
cap: usize,
}

所以当你调用 String::with_capacity :

pub fn with_capacity(capacity: usize) -> String {
String { vec: Vec::with_capacity(capacity) }
}

您所做的不仅仅是保留一段内存。

关于memory-management - `String::with_capacity()` 等于 `malloc` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44672193/

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