I was having trouble when using foo.value_or(bar())
in my code, because I wasn't expecting the function bar()
to be called when the optional variable foo
had a value. I've since found this question that explains that value_or()
doesn't use lazy evaluation.
Now I'm left wondering why that is, when lazy evaluation has always been a standard aspect of conditionals in C and C++. I find this very counter-intuitive, and I assume I wasn't the first and won't be the last to be tripped up by it. With the risk of asking to look into the minds of the people who devised std::optional
, is there a use case that explains why lazy evaluation would not be a good idea here?
foo.value_or(/*...*/)
is a function call. The argument expression will always be evaluated first, no matter what function is being called. You can see this directly in the syntax, whether it isvalue_or
or any other function doesn't matter. The core language doesn't have any lazily evaluated function arguments, so the library couldn't use them in such a way. The question you linked does explain though how to get a lazy evaluation with the help of a wrapped lambda. – Shipboard