3 ms·
You can justify the escape hatches for every feature in C++. The problem is that we eschew sensible defaults to handle the edge cases. Without going into a rust
by maccard 2y ago
You can justify the escape hatches for every feature in C++. The problem is that we eschew sensible defaults to handle the edge cases. Without going into a rust war, I think rust's unsafe is a great way to handle this - for 99% of use cases, you _really_ don't want to put an invalid enum value in there. But, in the number of cases where you do, you should have an escape hatch to do so.
If you could do:
my_enum_type foo(std::vector<char>& buf, int& offset)
{
// bounds check omitted for brevity
// return my_enum_type{buf{offset++]}; // outside an unsafe-style block would cause a compile error, or a throwing constructor. TBD
std::unsafe {
return my_enum_type{buf[offset++]};
}
}
you would reduce the possible impact areas to places where you explicitly want to do dangerous stuff.
Instead we end up with a feature that is a "zero cost abstraction" which just pushes the bookkeeping onto the user - every switch statemeent needs to handle the case where someone has passed in 42.
- gpderetta 2y agoI assure you I'm very critical of C++ bad defaults. But in this case I think it was the right solution. There were three options: 1. make invalid values UB. 2. make invalid values non-representable by enforcing checks. 3. enum class is just a strong integer typedef with named constants. Luckily 1 was reject: already too much UB. 2 would require runtime checking and was not considred viable by many; also it would prevent a lot of useful cases. 3 was the remaining option and was consistent with existing enum usage.