Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is this safe behaviour? #54749

Closed
faulesocke opened this issue Oct 2, 2018 · 1 comment
Closed

Is this safe behaviour? #54749

faulesocke opened this issue Oct 2, 2018 · 1 comment

Comments

@faulesocke
Copy link

faulesocke commented Oct 2, 2018

struct Refed;

impl Drop for Refed {
    fn drop(&mut self) {
        println!("Dropping!");
    }
}

struct Ref<'a>(&'a mut Val, Refed);

/*impl<'a> Drop for Ref<'a> {
    fn drop(&mut self) {
        println!("Dropping!");
    }
}*/

#[derive(Debug)]
struct Val;

impl Val {
    fn reference(&mut self) -> Ref {
        Ref(self, Refed)
    }
}

fn main() {
    let mut v = Val;
    println!("First reference");
    let r1 = v.reference();
    println!("Second reference");
    let r2 = v.reference();
    println!("Done");

    //println!("{:?}", r1.0);
}

It looks like two mutable references to the same object are in scope at the same time.

The behaviour is "fixed" when I uncomment the Drop implementation for Ref. Accessing the first reference after the second is in scope seems to be impossible as well (uncomment println).

However the behaviour feels a little bit whacky, is this really intentional?

I'm currently writing a safe wrapper around memory mapped files and was using a struct similar to the Ref above in order to statically prevent having multiple mappings for the same file in scope at the same time.

I wanted to make sure, that only one such mapping can exist at the same time (because memory needs to be flushed which happens in the drop() of the mapping before another mapping can be created) but it seems like Rust's type system does not prevent this.

@steveklabnik
Copy link
Member

Hi there! This isn't a bug. Since we try to keep the issue tracker solely for bugs, I'm going to close it, but if you'd like to discuss it more, please make a post to users.rust-lang.org. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants