Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

and i want to create objects like VAOs and Textures into structs

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Will the actual data of the object still remain in the RAM if i dont specifically call drop(struct_attribute) for all the attributes

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.

>Solution :

You do not need to manually drop other members when you implement drop, nor would you be able to.

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. If you did somehow drop it, rust would then proceed to drop it again after drop returns, causing a double free.

Drop doesn’t serve for dropping a type, despite it’s name. It’s more akin to a finalizer that runs code right before the type is dropped.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading