But what matters is run-time behavior for any input. And sorry, C++'s complexity still has the effect that the code is terrible: https://godbolt.org/z/vWfjjf8rP
In C, the compiler can remove all error paths: https://godbolt.org/z/GGMcc6bxv
> In C, the compiler can remove all error paths: https://godbolt.org/z/GGMcc6bxv
For what it's worth, if you actually use the same flags for the C++ example (in particular, -fsanitize-trap) the C++ compilers improve quite a bit, with Clang getting fairly close to the GCC C output (https://godbolt.org/z/M3z5EaGKj ; note that GCC doesn't seem to eliminate the std::optional::value() check unless you use -O3). But perhaps more interestingly, if you make a simplified std::optional that still uses C++-specific features both Clang and GCC produce output that is very close to that from C/GCC: https://godbolt.org/z/PhEW7eT8x
Removing I/O-related stuff makes this clearer:
C: https://godbolt.org/z/e71s9E63f
C++: https://godbolt.org/z/YnhdxYxY4 (Clang seems unable to eliminate the UBSan overflow check for some reason?)
Does make me wonder what exactly it is about std::optional that confuses the optimizers, and whether a similarly complex C maybe implementation can suffer from the same issues that std::optional appears to.
It's still a damned shame. Same for not being able to pass optional/unique_ptr/etc in a register.
We really need a trivially_relocatable attribute.
At least that is something we can agree on, C and C++ are both languages where developers could write robust code, and the large majority seldom does it.