Is it safe to acquire an `&'static T` from a thread local storage of `T` if `T: !Sync`?

In other words, is this function safe?

#![feature(negative_bounds)]

use std::mem;
use std::thread::LocalKey;

pub fn get_thread_local_static_ref<T>(key: &'static LocalKey<T>) -> &'static T
where
    T: !Sync,
{
    key.with(|value| unsafe { mem::transmute(value) })
}

If T is !Sync, &T is !Send, so although &'static T have static lifetime, you can only use it in the current thread.

OK, the Drop implementation maybe an issue, because it gains mutable access to the object, while it can also acquire an immutable reference to the object, which breaks the borrow-check rule.

It would also allow you to get a &'static _ to any fields, which may be Sync.

1 Like