Unexpected Behavior with std::optional and Move Semantics in C++20
I've hit a wall trying to I'm integrating two systems and Quick question that's been bugging me - I'm trying to configure I've been struggling with this for a few days now and could really use some help. I'm encountering an unexpected behavior while using `std::optional` in C++20, specifically when trying to move its contents to another `std::optional`. I have the following code snippet: ```cpp #include <iostream> #include <optional> struct MyStruct { int value; MyStruct(int v) : value(v) {} }; int main() { std::optional<MyStruct> opt1 = MyStruct(42); std::optional<MyStruct> opt2 = std::move(opt1); if (opt1.has_value()) { std::cout << "opt1 still has value: " << opt1->value << '\n'; } else { std::cout << "opt1 is now empty after move.\n"; } if (opt2.has_value()) { std::cout << "opt2 has value: " << opt2->value << '\n'; } else { std::cout << "opt2 is empty.\n"; } return 0; } ``` When I run this code, I expect `opt1` to be empty after the move and `opt2` to hold the value. However, I see `opt1 is now empty after move.` as expected, but `opt2 has value: 42` which is correct. The output looks fine. However, when I switch the order of constructing `opt1` and change its type to `std::optional<MyStruct*>`, the behavior changes unpredictably: ```cpp std::optional<MyStruct*> opt1 = new MyStruct(42); ``` In this case, `opt2` seems to retain ownership of the memory and trying to access the pointer directly after the move leads to a segmentation fault: ```cpp std::cout << "opt1 points to: " << *opt1 << '\n'; // This crashes! ``` I've tried using `std::shared_ptr` instead of raw pointers in `std::optional`, but I'm still confused about the semantics of moving raw pointers stored in an `std::optional`. Is this expected behavior? How can I safely manage resources when using `std::optional` with raw pointers? I would appreciate any guidance on best practices or explanations of the underlying mechanics here. My development environment is Windows. I'd really appreciate any guidance on this. I'd be grateful for any help. For context: I'm using C++ on Ubuntu 22.04. Could this be a known issue?