简体   繁体   English

如果我为结构编写自定义放置实现,是否需要指定“放置(项目)”? Rust

[英]Do I need to specify 'drop(item)' if i write a custom drop implementation for a struct? Rust

I'm working with OpenGL in rust currently.我目前在 rust 与 OpenGL 合作。

and i want to create objects like VAOs and Textures into structs我想将 VAO 和纹理之类的对象创建到结构中

now, i wrote a custom drop implementation that calls something like glDeleteTexture when the objects lifetime is finished so that it clears up the memory in VRAM.现在,我编写了一个自定义放置实现,当对象生命周期结束时调用类似glDeleteTexture的东西,以便它清除 VRAM 中的 memory。

Will the actual data of the object still remain in the RAM if i dont specifically call drop(struct_attribute) for all the attributes如果我不为所有属性专门调用drop(struct_attribute) ,object 的实际数据是否仍保留在 RAM 中

I'm expecting for rust to automatically call drop on every attribute but i just wanna make sure so that i dont waste my time or memory if im wrong.我期待 rust 在每个属性上自动调用 drop 但我只是想确保我不会浪费我的时间或 memory 如果我错了。

You do not need to manually drop other members when you implement drop, nor would you be able to.当你实现 drop 时,你不需要手动删除其他成员,你也不可能这样做。

Take for example:举个例子:

struct A {
    handle: i32,
    a: String,
    // ...
}

impl Drop for A {
    fn drop(&mut self) {
        // Do something with `handle`
        // ...

        // `a` will be dropped *after* this function returns automatically
    }
}

Drop::drop receives a &mut self , which makes it so you cannot (without unsafe or replacing the original value) drop self.a . Drop::drop收到一个&mut self ,这使得你不能(没有不安全或替换原始值)删除self.a If you did somehow drop it, rust would then proceed to drop it again after drop returns, causing a double free.如果您确实以某种方式丢弃了它,rust 将在drop返回后继续丢弃它,从而导致双重释放。

Drop doesn't serve for dropping a type, despite it's name. Drop不用于删除类型,尽管它的名称。 It's more akin to a finalizer that runs code right before the type is dropped.它更类似于在类型被删除之前运行代码的终结器。

drop is simply defined as fn drop<T>(_: T) {} , it does absolutely nothing special. drop被简单地定义为fn drop<T>(_: T) {} ,它没有做任何特别的事情。 Rust automatically picks up everything for you: almost every value is dropped by Rust (some exceptions include when the program diverges, but don't worry about it). Rust 自动为您拾取所有值:几乎每个值都被 Rust 丢弃(一些例外包括程序发散时,但不要担心)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM