I’m doing this, for experimental purposes (I want to allocate many objects in heap and measure the performance of this):
struct Foo {
x: u32
}
for i in 0..1000 {
let b = Box::new(Foo {x: i as u32});
let p = b.deref();
println!("Pointer: {:p}", p);
}
I’m getting this output:
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
...
Obviously, all addresses are the same, which means that right after an object is allocated it gets destroyed. How to prevent this? I want to keep the memory occupied by objects, not freed immediately.
>Solution :
You can use Box::leak to ensure the box doesn’t get freed.
fn main() {
struct Foo {
x: u32
}
for i in 0..1000 {
let b = Box::new(Foo {x: i as u32});
let p = Box::leak(b);
println!("Pointer: {:p}", p);
}
}
More generally std::mem::forget can be used to not run destructors