英文:
How to keep boxed objects in heap until the end of program execution?
问题
我正在进行这个实验(我想在堆上分配许多对象并测量其性能):
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);
}
我得到了这个输出:
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
...
显然,所有地址都相同,这意味着对象分配后立即被销毁。如何防止这种情况发生?我想保留对象占用的内存,而不是立即释放。
英文:
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.
答案1
得分: 1
你可以使用Box::leak
来确保这个盒子不会被释放。
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);
}
}
更一般地说,std::mem::forget
可以用来不运行析构函数。
英文:
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
答案2
得分: 1
要不释放对象的最佳方法是将其移动到其作用域之内:
fn main() {
let mut items = Vec::with_capacity(1000);
for x in 0..1000 {
let b = Box::new(Foo {x});
println!("Pointer: {:p}", b);
items.push(b);
}
}
英文:
To not free an object the best approach is to move it somewhere where it is in scope:
fn main() {
let mut items = Vec::with_capacity(1000);
for x in 0..1000 {
let b = Box::new(Foo {x});
println!("Pointer: {:p}", b);
items.push(b);
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论