std::optional
(no experimental, C++17 is upon us) defines two different interfaces to access it's optional member: the checked access (std::optional::value
) and the unchecked access (operator*
).
Using checked access has two potential drawbacks - first, it slows execution down because branch is executed, and second, in case of value not being there it will throw an exception, which could be undesirable in terms of control flow. While the second issue can be alleviated via explicit check for value present (std::optional::has_value
) before calling value, the run-time performance cost could still be there.
An unchecked access doesn't have performance cost associated to that, but can only be safely used if you know that the value is there by some other means (i.e. you checked has_value
before). Otherwise, behavior of the program is undefined, and we do not want that.
From the above, it should be obvious that the second snippet you have shown is excessive:
if (some_str.has_value())
some_str.value().c_str();
Does the check for value presence twice (at least semantically, compilers are likely to be able to optimize the second check away). Still, the clearer code
would be
if (some_str.has_value())
some_str->c_str();
vector::operator[]
vsvector::at
. – Nelsonnema