The Puzzle of Trying to Put an Object into a std::optional -- Raymond Chen

RaymondChen_5in-150x150.jpgThe std::optional<T> is a powerful tool for handling optional values, but assigning non-trivial types like Doodad to it can lead to unexpected compilation errors. This post explores why such assignments fail and unpacks the nuances of std::optional and type construction in modern C++.

The Puzzle of Trying to Put an Object into a std::optional

by Raymond Chen

From the article:

The C++ standard library template type std::optional<T> has one of two states. It could be empty (not contain anything), or it could contain a T.

Suppose you start with an empty std::optional<T>. How do you put a T into it?

One of my colleagues tried to do it in what seemed to be the most natural way: Use the assignment operator.

struct Doodad
{
    Doodad();
    ~Doodad();
    std::unique_ptr<DoodadStuff> m_stuff;
};

struct Widget
{
    std::optional<Doodad> m_doodad;

    Widget()
    {
        if (doodads_enabled()) {
            // I guess we need a Doodad too.
            Doodad d;
            m_doodad = d;
        }
    }
};

Unfortunately, the assignment failed to compile:

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.