Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When explicitly initializing std::optional's, should I use nullopt? [closed]

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).

like image 450
einpoklum Avatar asked Oct 14 '16 09:10

einpoklum


People also ask

What is std :: Nullopt in C++?

(since C++17) std::nullopt is a constant of type std::nullopt_t that is used to indicate optional type with uninitialized state.

Does std optional use dynamic memory?

According to the standard std::optional is prohibited to use dynamic memory for their direct members.

Does std optional allocate?

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 .

Is std :: optional thread safe?

Optional is immutable, so it's automatically thread safe.


2 Answers

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.

like image 195
paul-g Avatar answered Sep 17 '22 08:09

paul-g


It does not matter at all. Choose whatever makes your colleagues understand your code better.

like image 30
Kerrek SB Avatar answered Sep 21 '22 08:09

Kerrek SB