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

transmuting &dyn Trait to &(dyn Trait + Send) is unsound in general #1

Open
lcnr opened this issue Apr 25, 2023 · 0 comments
Open

transmuting &dyn Trait to &(dyn Trait + Send) is unsound in general #1

lcnr opened this issue Apr 25, 2023 · 0 comments

Comments

@lcnr
Copy link
Owner

lcnr commented Apr 25, 2023

the Send bound in &(dyn Trait + Send) is useless as &T is only Send for T: Sync. We may still rely on that Send bound in other ways however:

use std::rc::Rc;
use std::thread;

trait Trait {
    fn foo(&self)
    where
        Self: Send;
}

impl<T: Clone + 'static> Trait for T {
    fn foo(&self)
    where 
        Self: Send,
    {  
        let clone: T = self.clone();
        thread::spawn(move || clone.clone());
    }
}

fn main() {
    let rc = Rc::new(String::from("hello"));
    let x: &dyn Trait = &rc;
    loop {
        println!("strong count: {}", Rc::strong_count(&rc));
        let y: &(dyn Trait + Send) = unsafe { std::mem::transmute(x) };
        y.foo();
    }
}
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

1 participant