Difference between nullptr, {} and nullopt

Why can't i use nullptr instead of nullopt? And why {} translates like nullopt?

Upvotes: 4

Views: 5002

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

Why can't i use nullptr instead of nullopt?

Because they're different things. They mean something different, and they're used for something different.

It's necessary to have a distinct nullopt value for use with std::optional because nullptr already does something:

std::optional<int*> o;
o = nullptr;
assert( o.has_value() );
o = std::nullopt;
assert( !o.has_value() );

And why {} translates like nullopt?

(N.B. that is only true for std:optional not when using {} with other types.)

It does that because it's convenient to be able to say o = {} and have it Do The Right Thing™ and so the specification of std::optional is written to make it work.

Upvotes: 12

Caleth
Caleth

Reputation: 62684

  • optional<T> is not kind of pointer to T, it is a value that is either a T or is nothing. You cannot have a "dangling optional", or any other kind of "invalid" value, like you can with pointers and references.

  • nullptr is an object that can be converted to a value of any pointer type.

  • nullopt is an object that can be converted to a value of any optional type.

  • {} is (in a context expecting a value) an expression that means "a default constructed object of type T", where T is some type inferred from the context. If T is a pointer type, it will compare equal to nullptr. If T is an optional type, it will compare equal to nullopt. If T is an arithmetic type, it will compare equal to 0. If T is one of the standard container types, it will compare equal to other empty containers of that type.

Upvotes: 11

Related Questions