The article explains why std::optional::value_or eagerly evaluates its argument, causing unnecessary work, and shows how C++23's std::optional::or_else solves this by accepting a callable. It then presents a generic technique to achieve lazy evaluation for other STL functions such as std::map::try_emplace.
Background
Lazy initialization delays costly work until the result is actually needed, a technique often used to improve performance. In C++, function arguments are evaluated before the call, which can defeat laziness for APIs like std::optional::value_or.
- Source
- Lobsters
- Published
- Sep 13, 2026 at 08:50 PM
- Score
- 5.0 / 10