Solving the Puzzle of Trying to Put an Object into a std::optional -- Raymond Chen
Last time, we investigated the puzzle of why the compiler wouldn’t let us put an object into a std::optional
. It came down to the fact that the object is not copy-constructible, move-constructible, copy-assignable, or move-assignable, so there’s no way to put the temporary object into the std::optional
.
Solving the Puzzle of Trying to Put an Object into a std::optional
by Raymond Chen
From the article:
What we have to do is construct the object in place inside the
std::optional
. And the C++ standard library term for “construct an object inside a container” is “emplace”.struct Doodad { Doodad(); ~Doodad(); std::unique_ptr<DoodadStuff> m_stuff; }; struct Widget { std::optional<Doodad> m_doodad; Widget() { if (doodads_enabled()) { m_doodad.emplace(); } } };The parameters to
emplace
are whatever parameters you would have passed to theDoodad
constructor. In our case, we wanted the default constructor, so that means that we pass nothing toemplace()
.