Skip to content

Should there be a warning at compile time when implementing Drop trait with creation of same type inside? #55388

Description

@tom7980

I'm fairly new to Rust and have been working through the reference book recently, I've just covered the Drop trait implementation and thought it would be fun to see what happens if I create a new instance of the type I just dropped inside of the function.

Obviously this is completely nonsensical as nobody is going to do this but as you can probably tell this caused my stack to overflow and crash the program, would an error message at compile time be appropriate for something like this?

I can't see why anyone would want to initialise new variables inside of the drop trait but it's possible.

Example code of my implementation:

struct CustomSmartPointer {
    data: String,
}

impl CustomSmartPointer{
    fn new(s: String) -> CustomSmartPointer {
        CustomSmartPointer{
            data: s,
        }
    }
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self){
        println!("Dropping & creating new pointer");
        let c = CustomSmartPointer::new(String::from("test"));
        println!("New pointer created in memory");
    }
}

fn main() {
    let c = CustomSmartPointer::new(String::from("test"));
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions