4 ms·
I wouldn't exactly call it "normal", but that's partially because a lot of C# developers still don't know about the relatively new generic maths feature. Those
by kittoes 2y ago
I wouldn't exactly call it "normal", but that's partially because a lot of C# developers still don't know about the relatively new generic maths feature. Those who are familiar regularly "abuse" the system in a similar way because that's one of the major benefits of it. We don't necessarily reimplement basic arithmetic using the type system, but we regularly hoist generic constants into static properties in order to convince the compiler to behave the way we expect. For example: T.PopCount(value: T.AllBitsSet) is a safe and generic way to express the size of a binary integer as a constant.
- neonsunset 2y ago> 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.
- tialaramex 2y ago> Despite the name Why even have something labelled "Unsafe" which is in fact safe ? Genuine question. What lead to this choice?
- kittoes 2y agoThe 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.
- tialaramex 2y agoI 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.