2 ms·
C++ already has compiler-enforced null checking by virtue of not allowing non-pointer variables to be null. But sometimes we want a variable to be null and not
by furgooswft13 8y ago
C++ already has compiler-enforced null checking by virtue of not allowing non-pointer variables to be null. But sometimes we want a variable to be null and not be a pointer.
Consider:
struct stuff {
int required_value;
int optional_value;
}
What would you do if you had no value for optional_value? Probably use 0 or -1 but that can be problematic, and not even an option if optional_value is not a primitive type.
You could use int* optional_value instead and just assign NULL, but then you have to malloc/new and make sure to free/delete later.
You could use std::unique_ptr to handle memory management but you are still invoking dynamic memory.
std::optional allows you to have nullable variables without using pointers, even when hidden behind the scenes.
You could ask, what is the point of optional if you don't want to check if it is null? Well...I guess it's the same as no bounds checking, sometimes the programmer just knows. Most of the time, hopefully, a check will be done at some point, and subsequent accesses can skip the check.
- Gaelan 8y agoSo I guess C++'s optional type is for a completely different purpose from other languages, which is why I think I was confused.