How do I construct and use std::optional in C++?

In C++, std::optional is a powerful feature introduced in C++17 that represents an object that may or may not contain a value. It’s often used to handle cases where you want to signify that a value might be absent, thus providing a safer and more expressive way to manage optional data without resorting to pointers or special value indicators.

Constructing and Using std::optional

To use std::optional, you first need to include the header:

        #include <optional>
        #include <iostream>

        int main() {
            std::optional opt; // Default initialization, opt has no value
            if (!opt.has_value()) {
                std::cout << "opt is empty" << std::endl;
            }

            opt = 42; // Assign a value to opt
            if (opt.has_value()) {
                std::cout << "opt contains: " << *opt << std::endl; // Dereferencing to access value
            }

            // Reset the optional to be empty again
            opt.reset();
            if (!opt) {
                std::cout << "opt is now empty again" << std::endl;
            }

            return 0;
        }
    

std::optional C++17 optional type nullable types value semantics