一旦我分配了阵列,我该如何手动释放它?指针算法在不安全模式下是否可行?
就像在C++中一样:
double *A=new double[1000];
double *p=A;
int i;
for(i=0; i<1000; i++)
{
*p=(double)i;
p++;
}
delete[] A;
Rust中有任何等效的代码吗?
根据您的问题,如果您还没有这样做,我建议您阅读Rust Book.Idiomatic Rust几乎从不涉及手动释放内存.
至于相当于动态数组,你想要的Vector
.除非你做一些不寻常的事情,否则你应该避免在Rust中使用指针算法.您可以将上述代码编写为:
// Pre-allocate space, then fill it.
let mut a = Vec::with_capacity(1000);
for i in 0..1000 {
a.push(i as f64);
}
// Allocate and initialise, then overwrite
let mut a = vec![0.0f64; 1000];
for i in 0..1000 {
a[i] = i as f64;
}
// Construct directly from iterator.
let a: Vec = (0..1000).map(|n| n as f64).collect();
完全有可能在堆上分配一个固定大小的数组:
let a = Box::new([0.0f64; 1000]);
由于deref强制,您仍然可以将其用作数组:
for i in 0..1000 {
a[i] = i as f64;
}
您可以通过以下操作手动释放它:
std::mem::drop(a);
drop
takes ownership of the array, so this is completely safe. As mentioned in the other answer, it is almost never necessary to do this, the box will be freed automatically when it goes out of scope.