functional programming in C++0x

std::vector some_list;
int total = 0;
std::for_each(some_list.begin(), some_list.end(), [&total](int x) {
total += x;
});

Closure is supported. Fantastic!

But I think something here cannot be implemented because the lack of garbage collection in C++. The following gives an example:

std::function lambda_f;
{
int x = 10;
lambda_f = [x](int y) {return x + y;};
}

lambda_f(20);

What’s the result of this program? When we call lambda_f(20), there is no ‘x’ in the stack any more, so the result is undetermined. Without garbage collection, functional programming can never be completely supported. For example, the following program cannot be elegantly implemented in any no-garbage-collection language.

(defun f (x) (lambda (y) (+ x y)))
(funcall (f 20) 10)

Advertisements