If we want to represent an optional value, we can use std::unique_ptr (C++11) and heap allocation (nullptr denoting absence). However, this incurs a runtime cost and can fail (and throw). std::optional (C++17) will not allocate dynamic memory and only incurs the cost of storing a boolean. Compiler Explorer link: https://lnkd.in/eTP69EVF #cpp #cplusplus #coding #programming #dailybiteofcpp
I use optional for types that are not default constructible. I presume optional takes only tiny bit more space, and object when present gets constructed inplace using placement ctor. E.g. I have a generator of non default constructible type, and I use std::move() to deliver data from promise to the user. Before yielding first value the data in promise is default constructed, and std::optional works great in that case. I created a wrapping policy that automatically chooses optional if type is non default constructible.
I like the commented form better. It's more like an implementation agnostic interface.
Meta•5K followers
3ysometimes it's possible to store indicator of whether optional is present or absent without additional storage requirement. For example, tagged pointers can use lower bits that are 0s due to alignment requirements to store such state. I'm not sure if optional leverages alignment padding bits for such optimization, but it would be nice to have this as an option :)