I looked several online std::optional documentary over the internet. However I could not be able to find any direct comparison between two cases below:
case 1:
SomePointer* foo::get_some_pointer(cont int value) {
auto result = myMap.find(value);
if (result != myMap.end()) {
return const_cast<SomePointer*>(&result->second);
}
return nullptr;
}
case 2
std::optional<SomePointer*> foo::get_some_pointer (cont int value) {
auto result = myMap.find(value);
if (result != myMap.end()) {
return std::optional<SomePointer*>{&result->second};
}
return std::nullopt;
}
What are the advantages/disadvantages of the case 1 over the case 2(nullopt over nullptr) ?
nullptr
. Butstd::optional
becomes really helpful if you return some objects or values which do not have 'empty' state.nullptr
andstd::nullopt
, more choice :). It's more usual to usestd::optional<SomePointer>
without the*
in there.const_cast
is extremely sketchy, by the way.std::optional<SomePointer*>
, it has three states: has a valid pointer, has anullptr
, has astd::nullopt
. Your code carefully returns valid pointer orstd::nullopt
... but the caller or code thereafter ought to still be wary of the "never happen"nullptr
possibility. (Well, could have a dangling pointer, or a wild pointer, or uninitialized pointer... I'm ignoring those scenarios.)std::optional<std::reference_wrapper<SomePointer>>
which avoids thenullptr
state entirely, and still has the packaging behavior, and is self-documenting code. (SomePointer is probably poorly named, since I presume it isn't a pointer.)