4 ms·
So, so many ways in which this is defective compared to actual sum types, some of them were already listed, but to me the most crucial, even if mostly about th
by tialaramex 4y ago
So, so many ways in which this is defective compared to actual sum types, some of them were already listed, but to me the most crucial, even if mostly about theory rather than practice, is valueless_by_exception.
The choice to provide exceptions everywhere as a error handling means C++ is obliged to admit that your std::variant may not have a value at all. Which blows up all of your type safety. In Rust I can say that this Pet is either a Dog or a Cat, and it cannot be neither, but in C++ std::variant of a Cat and a Dog might nevertheless be valueless_by_exception anyway. What can you do about that? I guess you could throw an exception...
In Rust if X is either A or B, and Y is either C or D, and Z is either E or F, then a structure with X, Y and Z has only eight possible states. In C++ this structure has 27 possible states because of exceptions.
- dureuill 4y agoI get the "theoretical" point, but the issues I encountered in practice are closer to the ones I listed in my response than to valueless_by_exception (which I never encountered, I think?). Wrt type safety we had more pressing issues with C++ (use after move, implicit conversions, ...)
- planede 4y agoExceptions are an optional feature. Also, if sufficient amount of constructors are marked noexcept, then the variant can never be valueless. Implementations are optimized accordingly. You also don't have to handle the exception, in which case you won't access the variant again anyway. Or it gets handled where the variant is teared down. It's very unlikely that it gets handled where the variant is constructed or assigned to, making it a non-issue.
- pjmlp 4y agoThey aren't as per ISO C++, even though all compilers allow to disable them in non standard conforming ways.
- planede 4y agoI meant exceptions as a user of the language. You can decide not to throw. You can mark functions noexcept. Granted, it's more awkward when you consume 3rd party libraries, but you can still wrap them in noexcept interfaces and be fine with terminating when an exception is actually thrown or do something else. Not much different to a panic.