如何在程序执行结束之前将堆中的盒装对象保留?

huangapple go评论111阅读模式
英文:

How to keep boxed objects in heap until the end of program execution?

问题

我正在进行这个实验(我想在堆上分配许多对象并测量其性能):

  1. struct Foo {
  2. x: u32
  3. }
  4. for i in 0..1000 {
  5. let b = Box::new(Foo {x: i as u32});
  6. let p = b.deref();
  7. println!("Pointer: {:p}", p);
  8. }

我得到了这个输出:

  1. Pointer: 0x600000780000
  2. Pointer: 0x600000780000
  3. Pointer: 0x600000780000
  4. Pointer: 0x600000780000
  5. Pointer: 0x600000780000
  6. ...

显然,所有地址都相同,这意味着对象分配后立即被销毁。如何防止这种情况发生?我想保留对象占用的内存,而不是立即释放。

英文:

I'm doing this, for experimental purposes (I want to allocate many objects in heap and measure the performance of this):

  1. struct Foo {
  2. x: u32
  3. }
  4. for i in 0..1000 {
  5. let b = Box::new(Foo {x: i as u32});
  6. let p = b.deref();
  7. println!("Pointer: {:p}", p);
  8. }

I'm getting this output:

  1. Pointer: 0x600000780000
  2. Pointer: 0x600000780000
  3. Pointer: 0x600000780000
  4. Pointer: 0x600000780000
  5. Pointer: 0x600000780000
  6. ...

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来确保这个盒子不会被释放。

  1. fn main() {
  2. struct Foo {
  3. x: u32
  4. }
  5. for i in 0..1000 {
  6. let b = Box::new(Foo {x: i as u32});
  7. let p = Box::leak(b);
  8. println!("Pointer: {:p}", p);
  9. }
  10. }

更一般地说,std::mem::forget可以用来不运行析构函数。

英文:

You can use Box::leak to ensure the box doesn't get freed.

  1. fn main() {
  2. struct Foo {
  3. x: u32
  4. }
  5. for i in 0..1000 {
  6. let b = Box::new(Foo {x: i as u32});
  7. let p = Box::leak(b);
  8. println!("Pointer: {:p}", p);
  9. }
  10. }

More generally std::mem::forget can be used to not run destructors

答案2

得分: 1

要不释放对象的最佳方法是将其移动到其作用域之内:

  1. fn main() {
  2. let mut items = Vec::with_capacity(1000);
  3. for x in 0..1000 {
  4. let b = Box::new(Foo {x});
  5. println!("Pointer: {:p}", b);
  6. items.push(b);
  7. }
  8. }
英文:

To not free an object the best approach is to move it somewhere where it is in scope:

  1. fn main() {
  2. let mut items = Vec::with_capacity(1000);
  3. for x in 0..1000 {
  4. let b = Box::new(Foo {x});
  5. println!("Pointer: {:p}", b);
  6. items.push(b);
  7. }
  8. }
  9. </details>

huangapple
  • 本文由 发表于 2023年3月31日 17:26:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定