Unexpected Behavior of std::optional with Custom Types in C++20
I keep running into I'm encountering unexpected behavior when using `std::optional` with a custom type in C++20. I have a class `Person` that contains a `std::string` for the name and an `int` for age. The issue arises when I try to initialize an `std::optional<Person>` and later reset it. Hereโs the code snippet: ```cpp #include <iostream> #include <optional> #include <string> class Person { public: Person(const std::string& name, int age) : name(name), age(age) {} friend std::ostream& operator<<(std::ostream& os, const Person& p) { os << "Name: " << p.name << ", Age: " << p.age; return os; } private: std::string name; int age; }; int main() { std::optional<Person> personOpt = std::make_optional<Person>("Alice", 30); std::cout << *personOpt << std::endl; // Outputs: Name: Alice, Age: 30 personOpt.reset(); // Resetting the optional if (!personOpt) { std::cout << "Optional is empty after reset." << std::endl; } // Attempt to access after reset std::cout << *personOpt << std::endl; // Should throw an exception } ``` When I run the program, it correctly indicates that the optional is empty after the reset. However, when I try to access it again using `*personOpt`, it leads to undefined behavior instead of throwing an exception. I expected that dereferencing an empty optional would throw a `std::bad_optional_access` exception, but itโs not behaving as expected. I've verified that my compiler (GCC 11.1.0) supports C++20 features. Has anyone else encountered this issue? Whatโs the correct way to handle this case? Am I missing something in the initialization or the reset process? I'm coming from a different tech stack and learning C++. How would you solve this? Any pointers in the right direction?