Pre-RFC: Deprecate then remove `static mut`

I think this needs some example code, I have the feeling it's comparing static mut to the existing features like Cell, not to the direct replacements like SyncUnsafeCell, a quick testcase in godbolt doesn't show any extra copies happening with that: https://godbolt.org/z/jPazdd33M, as expected because these are fundamentally doing the same operation (while the existing features have additional overhead because of how they ensure the safety).

EDIT: Copying the relevant message from the survey so others don't have to go spelunking for it too:

6 Likes

I can not give a concrete example (as I didn't write that answer in the survey). But I believe @Nemo157 figured out the likely explanation.

As for placement new, it was obvious to me due to my low level C++ background. I should however not have assumed everyone has such a background.

Placement new is one of the more obscure features of C++. Unlike a standard new (which allocates memory from the allocator and then calls the constructor to initialise said memory with the object you requested), it constructs the object in place at the pointer you told it to. It is the caller who is responsible for ensuring that the memory is indeed allocated and sufficiently sized, aligned etc.

Placement new finds uses in implementing allocators, memory pools, object pools and similar. It is rare you would use it from application code, though I could see uses in freestanding code (c/c++ version of no-std) where you don't have an allocator.

This is one area where rust give you less control in general. You have to hope that the compiler is smart enough to get rid of the copies.

I'd love to do this, but there are some things that are only allowed in the initializer of a static mut, but not anywhere else (most notably, returning mutable references). I guess we could keep enough information around to let the compiler handle these special cases, but otherwise remove the concept of mutable statics

Could you give a code example of what kind of expression static mut initializers can evaluate, but (non-mut) static (wrapped with SyncUnsafeCell::new) cannot? I can’t quite imagine how “returning mutable references” can be used there.

1 Like
static mut FOO: &mut [u8] = &mut[42, 43, 44];

Requires knowing that we are in a static mut, because we definitely don't allow mutable references in statics right now. We're considering changing that though, as you can't use them mutably anyway, unless wrapped in a mutexes or other Sync data structure (see Mutable reference protected by a mutex in static context is considered UB · Issue #120450 · rust-lang/rust · GitHub)

I guess it might be related, there is an unsound crate that is used for some reason, and it involves static mut:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.