Unexpected behavior with std::optional in C++20 when used with emplace and move semantics
I've been banging my head against this for hours. I'm encountering a puzzling issue while working with `std::optional` in C++20. I have a class `User` that contains a `std::optional<std::string>` as a member variable. I'm trying to use `emplace` to initialize the optional with a value conditionally, but it seems that the existing value in `std::optional` is not being replaced as expected. Here's a simplified version of my code: ```cpp #include <iostream> #include <optional> #include <string> class User { public: std::optional<std::string> name; void setName(const std::string& newName) { if (name) { std::cout << "Replacing existing name: " << *name << '\n'; } name.emplace(newName); } }; int main() { User user; user.setName("Alice"); // First call, should set the name user.setName("Bob"); // Second call, should replace the name if (user.name) { std::cout << "Current name: " << *user.name << '\n'; } return 0; } ``` When I run this code, I expect the output to show that the name "Alice" is being replaced by "Bob". However, the output is: ``` Replacing existing name: Alice Current name: Alice ``` This indicates that the `std::optional` is not holding the new value after the second call to `setName`. I’ve double-checked the function signature and usage of `emplace`, and I believe it's supposed to construct the value directly in the optional container. I've also tried using `reset()` before calling `emplace()`, but that didn't change the behavior. I'm using GCC 11.2 and compiling with `-std=c++20`. Is there something I'm missing regarding how `std::optional` works with move semantics or emplace operations? Any insights or suggestions would be appreciated! I'm working on a API that needs to handle this. Any ideas what could be causing this? This is part of a larger API I'm building. Could someone point me to the right documentation?