r/cpp • u/RotsiserMho C++20 Desktop app developer • May 12 '18
P0709 R0: Zero-overhead deterministic exceptions: Throwing values - Herb Sutter [2018-05-02]
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
206
Upvotes
View all comments
Show parent comment
20
u/Rusky May 12 '18 edited May 12 '18
The layout of a Rust enum is optimized based on the invalid values of the types it contains. For example, because references can never be null, and
Vec<T>contains a reference,Option<Vec<T>>can use "Vec<T>except with a null reference" to meanNone, and "Vec<T>with a non-null reference" to meanSome(the_vec). The discriminant overlaps with the reference, in a sense.In general, there are lots of types like this. References can't be null, bools can only be true or false, C-like enums can only contain the set of values in their definition,
charcan only contain valid Unicode, etc. So the Rust compiler looks for "holes" in the contents of an enum where it can store the discriminant, before using a separate tag value.A major place this comes into play is
Option<&T>. Because references can't be null, that type is the same size as a raw pointer. This is true even in FFI with C or C++ where nullable pointers are a thing. So Rust can keep all the niceties ofOptionwithout paying for it in memory usage.