Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::optional set to std::nullopt when it is declared as a local variable and not explicitly initialized?

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?

like image 640
jhourback Avatar asked Oct 24 '25 14:10

jhourback


1 Answers

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.

like image 162
cigien Avatar answered Oct 27 '25 02:10

cigien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!