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
emplaceare whatever parameters you would have passed to theDoodadconstructor. In our case, we wanted the default constructor, so that means that we pass nothing toemplace().

Since its introduction,
We all know that every ‘,’ matters in this language, so I decided to talk directly about that character today. So, how much impact can be for such a small little character?
The topic of this post is to show different ways to ensure that a class is either non-moveable or non-copyable.
Jonathan Müller attended the fall 2024 meeting of the ISO C++ standardization committee in Wrocław, Poland. This was the fifth meeting for the upcoming C++26 standard and the feature freeze for major C++26 features.