Segmentation Fault When Using std::variant with std::optional in C++20
I'm having trouble with I'm trying to figure out I'm experiencing a segmentation fault when trying to access a value from a `std::variant` that contains `std::optional` types... The code looks like this: ```cpp #include <iostream> #include <variant> #include <optional> using namespace std; int main() { variant<optional<int>, optional<double>> v; v = optional<int>(5); if (holds_alternative<optional<int>>(v)) { cout << "Value: " << get<optional<int>>(v).value() << endl; } return 0; } ``` On some occasions, when I attempt to access the value using `get<optional<int>>(v).value()`, I receive a segmentation fault instead of the expected output. I've checked the variant's state with `holds_alternative` and it confirms it holds an `optional<int>`. It seems to work fine if I check the optional's state using `has_value()` before calling `value()`. For instance, if I change the code to: ```cpp if (holds_alternative<optional<int>>(v) && get<optional<int>>(v).has_value()) { cout << "Value: " << get<optional<int>>(v).value() << endl; } ``` ...then it runs without issues. But I am unsure why `value()` can cause a segmentation fault if `has_value()` is not checked beforehand. Is there a particular reason this behavior occurs in C++20? I am using GCC 10.2.0 with the `-std=c++20` flag. What best practices should I follow when using `std::variant` with `std::optional` to avoid such issues? This is part of a larger web app I'm building. For reference, this is a production desktop app. Is there a better approach? For context: I'm using Cpp on Ubuntu 20.04. How would you solve this?