Skip to content

Last updated:2026-10-12

C++ Lazy Evaluation Idiom


In software development, lazy evaluation (lazy evaluation or call-by-need) is a powerful technique that lets us postpone the evaluation of an expression until the moment it is actually needed.

This technique is especially useful when dealing with large data sets or computations that need to be performed dynamically.

1. What Is Lazy Evaluation?

Lazy evaluation means deferring the evaluation of expressions until they are actually needed. The advantage of this technique is that it can improve a program's efficiency and performance, especially when processing large data sets or when dynamic computation is required.

Lazy evaluation is usually implemented through deferred function calls or deferred expression evaluation. This means that an expression's evaluation is postponed until the expression is used, rather than being executed immediately at the point where it is defined.

2. Several Implementation Methods

In C++, we have several ways to implement lazy evaluation. Here are some common ones:

  1. Lambda expressions: a lambda expression can represent an anonymous function and perform the deferred computation wherever it is needed.
auto delayedCalculation = []() {
    std::cout << "延迟计算" << std::endl;
    return 42;
};
  1. std::function: std::function can be used to wrap a function so that its execution can be deferred to some later point in time.
std::function<int()> delayedCalculation = []() {
    std::cout << "延迟计算" << std::endl;
    return 42;
};
  1. std::bind: std::bind can bind a function together with its arguments and produce a callable object, deferring the function call.
auto delayedCall = std::bind(delayedCalculation, 42);
  1. Function pointers: through a pointer to a function, the corresponding function can be called when needed, achieving lazy evaluation.
void delayedCalculation() {
    std::cout << "延迟计算" << std::endl;
}

void (*funcPtr)() = &delayedCalculation;
(*funcPtr)();
  1. Lazy evaluation: lazy evaluation is a paradigm of deferred computation that delays the evaluation of an expression until it is truly needed.
auto it = std::begin(vec);
std::cout << "第一个元素:" << *it << std::endl;
  1. Generators: a generator is a technique for lazily producing a sequence, allowing the elements of the sequence to be produced on demand instead of producing them all at once.
std::vector<int> generateSequence(int n) {
    std::vector<int> result;
    for (int i = 0; i < n; ++i) {
        result.push_back(i);
    }
    return result;
}

Beyond these, what other implementations are there? Feel free to discuss it with me.

Comments