1+++ 2title = "`lazy<T>/atomic_lazy<T>`" 3description = "A lazily evaluated coroutine awaitable with Outcome customisation." 4+++ 5 6This is very similar to {{% api "eager<T>" %}}, except that execution of the 7`lazy<T>` returning function suspends immediately. Functions which return `lazy<T>` 8are therefore suitable for tasks which you need to instantiate right now, but whose 9execution will occur elsewhere e.g. in a separate kernel thread. Because of the very 10common use case of using worker threads to execute the body of lazily executed 11coroutines, most people will want to use `atomic_lazy<T>` instead of `lazy<T>`. 12 13`atomic_lazy<T>` is like `lazy<T>`, except that the setting of the coroutine result 14performs an atomic release, whilst the checking of whether the coroutine has finished 15is an atomic acquire. 16 17`lazy<T>` has similar semantics to `std::lazy<T>`, which is being standardised. See 18https://wg21.link/P1056 *Add lazy coroutine (coroutine task) type*. 19 20Example of use (must be called from within a coroutinised function): 21 22```c++ 23lazy<int> func(int x) 24{ 25 co_return x + 1; 26} 27... 28// Always suspends perhaps causing other coroutines to execute, then resumes. 29int r = co_await func(5); 30``` 31 32`lazy<T>` has special semantics if `T` is a type capable of constructing from 33an `exception_ptr` or `error_code` -- any exceptions thrown during the function's body 34are sent via `T`, preferably via the error code route if {{% api "error_from_exception(" %}}`)` 35successfully matches the exception throw. This means that a {{% api "basic_result<T, E, NoValuePolicy>" %}} 36or {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}} where one of its types is 37is compatible will have its `.error()` or `.exception()` set. 38 39Note that `lazy<T>` does not otherwise transport exception throws, and rethrows 40any exceptions thrown within the coroutine body through the coroutine machinery. 41This does not produce reliable consequences in current C++ compilers. You should 42therefore wrap the coroutine body in a `try...catch` if `T` is not able to transport 43exceptions on its own. 44 45*Requires*: C++ coroutines to be available in your compiler. 46 47*Namespace*: `BOOST_OUTCOME_V2_NAMESPACE::awaitables` 48 49*Header*: `<boost/outcome/coroutine_support.hpp>` 50