Boost logo

Boost :

From: Jaakko Jarvi (jajarvi_at_[hidden])
Date: 2004-03-04 10:13:18


On Thu, 4 Mar 2004, Shannon Stewman wrote:

> How is this worse than:
>
> static int* i( new int(2378) );
>
> typedef (void *)(void) void_fxn;
>
> void something(void) { *i += 5; }
>
> void_fxn return_something(void)
> {
> *i = 0;
> return &something;
> }
>
> void exercise_something(void)
> {
> void_fxn fxn = return_something();
> delete i;
> fxn();
> }
>
> Admittedly this feels a bit contrived, but errors like this happen not
> too inrequently in C/C++. Take the contrived but quite legal case:
>
> void bad_function(void)
> {
> int* i1 = new int;
> *i1 = 0;
>
> delete i1;
>
> *i1 = 2378; // shouldn't be legal
> }
>
> When you play with explicit heap management, you're responsible for
> making sure the object's lifetime is longer than its references (or
> pointers). If you can do this with named functions and function
> pointers, what's the objection to creating a similar problem in lambda
> functions?
>

My example was a bit contrived too.
Here's another example (with imaginary syntax):

auto foo() {
  int i;
  return auto(int x) { return i + x; }
}

auto x = foo();
x(1); // is i still there?

So my point was that
equipped with more (seemingly easy) tools,
erroneous code may be more likely. We can get similar effects in the
language now, but one must work harder to stumble into them.

In my view, the choices for dealing with lambdas in C++ are:

1. Not care about the dangers. With power comes responsibility.
2. Restrict lambdas enough to make them safer but less powerful
  - Cannot store lambdas in data structures
  - Cannot return lambdas from functions
3. Add real closures to C++
  - E.g. force all variables that occur free in lambdas to be allocated
   on the heap (and add some kind of garbage collection for those ...)

Of these:

1. May very well be the choice for C++, it is in the spirit of the
language :)

2. Might be a compromise that would still be useful.
(you could e.g. pass a lambda to an STL algorithm)

3. seems hard.

  Best, Jaakko


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk