Content
- 1. Code example
- 2. Result
Suppose we wrote a function that calculates some value or uses a function to calculate this value, while the function_ which calculates the value is quite expensive to calculate and works for a long time. In this case, we call the lambda function several times in some code.
To avoid multiple calls to the heavy function, we can cache the value that the heavy function returns.
Code example
#include <iostream> #include <string> using namespace std; int heavy_calc(int base) // heavy function that we want to call once { cout << "heavy_calc" << std::endl; // sleep(+100500 years) return base * 25; } void calclulateValue(int base) { // The following construction allows you to cache the result of executing a heavy function for the duration of one call to calclulateValue auto foo { [cache = heavy_calc(base)]() { return cache; } }; // We call the lambda twice with the cached heavy calc value // In this case, heavy calc is called only once int fooFoo = foo() + foo(); cout << fooFoo << std::endl; } int main() { // Call calclulateValue twice with a different base value, // to show that the cache is reset every time calclulateValue is called calclulateValue(1); calclulateValue(10); return 0; }
Result
heavy_calc 50 heavy_calc 500