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. – Footstallnullptr
andstd::nullopt
, more choice :). It's more usual to usestd::optional<SomePointer>
without the*
in there. – Bigwigconst_cast
is extremely sketchy, by the way. – Citationstd::optional
allows returning objects by value (which you don't in your example, though) and still have the option available of not returning anything at all... – Romainestd::optional
requires the programmer to unpackage it. The compiler won't give a peep if the code blithely dereferences the pointer and didn't bother to ensure it isn'tnullptr
. But putting a pointer in astd::optional
seems like a bad conflation. Better would be to make a smart pointer that disallows (throws) operations onnullptr
. – Radtkestd::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.) – Radtkestd::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.) – Radtke