The Puzzle of Trying to Put an Object into a std::optional -- Raymond Chen
The 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::
has one of two states. It could be empty (not contain anything), or it could contain aoptional<T> T
.Suppose you start with an empty
std::
. How do you put aoptional<T> 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: