CodexBloom - Programming Q&A Platform

std::optional not behaving as expected with custom types in C++20

πŸ‘€ Views: 1141 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-01
cpp stdoptional c++20 custom-types

I'm getting frustrated with I'm trying to figure out I'm working on a project and hit a roadblock. I'm wondering if anyone has experience with This might be a silly question, but I'm working with an scenario with `std::optional` in C++20 when trying to use it with a custom class. The class has a non-trivial constructor and destructor, which I thought would be handled correctly by `std::optional`. However, I am getting a runtime behavior when the `optional` goes out of scope. Here’s my custom class definition: ```cpp class MyClass { public: MyClass() { std::cout << "Constructor called" << std::endl; } ~MyClass() { std::cout << "Destructor called" << std::endl; } MyClass(const MyClass&) = delete; // Disallow copy MyClass& operator=(const MyClass&) = delete; }; ``` And I'm using `std::optional` like this: ```cpp std::optional<MyClass> myOptional; myOptional.emplace(); // This should construct MyClass ``` However, when `myOptional` goes out of scope, I receive the following behavior: ``` Unexpected exception: std::bad_optional_access ``` I've tried to verify that the constructor is indeed called, but I don't see any destructor message on the console, leading me to think that `MyClass` may not be destructed correctly. I also checked that my compiler (g++) supports C++20 features properly (version 10.2.0). What could be causing this behavior? Are there specific considerations or best practices when using `std::optional` with custom types that I might be missing? My development environment is Ubuntu. I'd really appreciate any guidance on this. I'm using Cpp latest in this project. I appreciate any insights! This is for a application running on macOS. I'm working on a service that needs to handle this. Any advice would be much appreciated. This is for a desktop app running on Debian.