DEV Community

Cover image for std::optional? Proceed with caution!

std::optional? Proceed with caution!

Pawel Kadluczka on January 15, 2024

The std::optional type is a great addition to the standard C++ library in C++ 17. It allows to end the practice of using some special (sentinel) va...
Collapse
 
pgradot profile image
Pierre Gradot • Edited

I've never been of a fan this implicit conversion to boolean that std::optional exposes. I always use .has_value(). The code may seem heavier to some people, but I believe the intent is much clearer and maintainability is improved.

You post is a good example of "explicit is better that implicit" (and maybe why you should not provide implicit conversion operators / constructors in C++ :)

Collapse
 
moozzyk profile image
Pawel Kadluczka

Yes, this implicit conversion (along with dereferencing with *) is a trap. But it is what it is, and it's not going to change. We use optional types a lot and I encourage everyone to always use .has_value() and .value() for clarity.