Šimon Tóth’s Post

View profile for Šimon Tóth

C++ Educational Content Creator | 20 years of Software Engineering experience distilled into digestible daily posts

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

  • text

sometimes 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 :)

Sonia K.

Principal Systems Architect &…5K followers

3y

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.

Farid Mehrabi

Self-employed499 followers

3y

I like the commented form better. It's more like an implementation agnostic interface.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories