Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> For example: T.PopCount(value: T.AllBitsSet) is a safe and generic way to express the size of a binary integer as a constant.

Despite the name, 'Unsafe.SizeOf<T>()` is the safe and preferred way to do this - it is guaranteed to be a compiler constant (in the past you'd say "JIT constant" but you can no longer assume that with the advent of NativeAOT).

It's a bit unfortunate because much like with MemoryMarshal, not all methods are equally unsafe. Some are benign or safe like this one, same are Unsafe.As or, worse, Unsafe.AsPointer.



> Despite the name

Why even have something labelled "Unsafe" which is in fact safe ? Genuine question. What lead to this choice?


The reasoning is generally that using SizeOf implies one is doing unsafe things. Why do you need the size of something in managed code? What would you do with that information?

Not that I necessarily agree with the decision myself, but that's the argument made by others.


I cannot get behind that argument, it seems to me that it ends up needlessly marking work as dangerous and in need of proper review when it's actually not at all remarkable and so you teach people these reviews aren't really important, it's probably just another false positive.

Rust spent lots of effort on making sure these lines are in the right place. The current work to try to "make C++ safer" is likely to ban taking a 32-bit unsigned integer and treating that as a 32-bit IEEE floating point value because it can invoke Undefined Behaviour in their language. Meanwhile in Rust that exact feature is not only safe, it's a pure function named `f32::from_bits` because 0x40000000 literally is 2.0, it's never any other value, there's no actual danger here, you just need to fix your programming language but C++ would rather waste your time on this non-existent problem.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: