Horizon Posted December 11, 2024 Share Posted December 11, 2024 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::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: View the full article Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.