An std::optional<T>
can be initialized to the disengaged state like so:
std::optional<int> oi { nullopt };
but also like so:
std::optional<int> oi { };
and similarly for assignment (oi = {}
or oi = nullopt
).
Other than personal preference / sense of aesthetics, is there a difference between these which should make me prefer one over the other? Or does it not matter at all?
Note: I'm asking about cases where I want to explicitly initialize the optional, rather than default-initialize it (e.g. for emphasis).
(since C++17) std::nullopt is a constant of type std::nullopt_t that is used to indicate optional type with uninitialized state.
According to the standard std::optional is prohibited to use dynamic memory for their direct members.
What's more, std::optional doesn't need to allocate any memory on the free store. std::optional is a part of C++ vocabulary types along with std::any , std::variant and std::string_view .
Optional is immutable, so it's automatically thread safe.
They both have the same effect - I would prefer the simplest form (KISS), but it is subjective, pick one and be consistent. You may also wish to be consistent with how you treat other objects in your code, do you normally rely on default initialization (e.g. int i{}
vs int i{0}
)?
Personally when I see redundant code, like initalizing an object to its default value explicitly, it does reduce my confidence in the author by a slight margin - does the author really understand what he is doing and trying to be extra safe / explicit / readable, or was he simply too lazy to read the documentation? It makes me wonder, does the author understand what happens when he writes std::vector<std::optional> v(n)
, or more complex examples? If this is a documented decision, in a coding style, then all is fine, I can understand the need to improve readability.
It does not matter at all. Choose whatever makes your colleagues understand your code better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With