std::optional Initialization scenarios with Custom Class in C++20
I've searched everywhere and can't find a clear answer. Quick question that's been bugging me - I'm working with an scenario while trying to initialize a `std::optional` with a custom class in C++20. The class has a non-default constructor, and I'm getting a compilation behavior when I try to create the optional without providing initial values. Here's a simplified version of my code: ```cpp #include <optional> #include <iostream> class MyClass { public: MyClass(int value) : value(value) {} int getValue() const { return value; } private: int value; }; int main() { std::optional<MyClass> opt; // This line causes a compilation behavior. if (opt) { std::cout << "Value: " << opt->getValue() << '\n'; } else { std::cout << "Optional is empty." << '\n'; } return 0; } ``` When I compile this with `g++ -std=c++20 main.cpp`, I get the behavior: ``` behavior: no matching constructor for initialization of 'MyClass' ``` I understand that `std::optional` requires a default constructor for the type it's holding, but my class doesn't have one. I tried adding a default constructor, but that doesn't make sense for my use case since I want to ensure that `MyClass` is always initialized with a valid value. I've also tried using `std::make_optional`: ```cpp std::optional<MyClass> opt = std::make_optional<MyClass>(10); ``` But I want to be able to declare an optional variable without immediately initializing it. Is there a way to handle this scenario while adhering to best practices in C++20? What changes do I need to make in order for this to work effectively without compromising the design of my class? This is part of a larger service I'm building. Thanks in advance! For context: I'm using C++ on Linux. I'd really appreciate any guidance on this. I'm working on a service that needs to handle this.