When an int
is declared locally (but not initialized or assigned to), it is of undefined value. When std::optional<int>
is declared locally without an explicit initialization, does the same apply? Is it always std::nullopt
, or is it of undefined value?
Asked
Active
Viewed 1,426 times
1

jhourback
- 4,381
- 4
- 26
- 31
-
related/dupe: https://stackoverflow.com/questions/57964217/stdoptional-construct-empty-with-or-stdnullopt – NathanOliver Aug 04 '20 at 18:51
1 Answers
4
From the reference for std::optional
constructors:
constexpr optional() noexcept;
constexpr optional( std::nullopt_t ) noexcept;
Constructs an object that does not contain a value.
So yes, a default initialized std::optional
has no value, but it's not indeterminate.

cigien
- 57,834
- 11
- 73
- 112
-
Is the constructor called when the object is declared locally but not initialized? – jhourback Aug 04 '20 at 19:00
-
1
-
@jhourback "Is the constructor called when the object is declared locally but not initialized?" - Yes, the default constructor is called in that case. – Jesper Juhl Aug 04 '20 at 19:02
-
2My interpretation is that an `int` declared locally will NOT be default-initialized, but that an `std::optional` declared locally will be default-initialized by calling the default constructor. Is this correct? – jhourback Aug 04 '20 at 19:05
-
2Yes, an `int` that is uninitialized has an indeterminate value. Note that this is still default-initialization of the int, it's just that default-initialization leaves the int with an indeterminate value. – cigien Aug 04 '20 at 19:06
-
2@jhourback An `int` declared as `int i;` *is* default initialized, it's just that `int`s don't have constructors and "default initialization" in that case means "has indeterminate value". `std::optional` on the other hand *does* have a default constructor that initialises the object to the value of `std::nullopt`. Just like the default constructor of a `std::string` initialises the object to an empty string. Default initialization is *not* the same as *zero initialization*. – Jesper Juhl Aug 04 '20 at 19:11