1

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?

jhourback
  • 4,381
  • 4
  • 26
  • 31

1 Answers1

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
    Yes, declaring an `optional` object does call the constructor. – cigien Aug 04 '20 at 19:01
  • @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
  • 2
    My 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
  • 2
    Yes, 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