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

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

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>



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:

确定