Boost logo

Boost :

From: Shannon Stewman (stew_at_[hidden])
Date: 2004-03-04 06:03:18


On Thu, Mar 04, 2004 at 12:03:25AM -0500, Jaakko Jarvi wrote:

> int* i = new int;
>
> *i = 1;
>
> function<int,int> f = (*i += _1);
>
> delete i;
>
> f(1); // *i is gone here
>
> Similar problems occur if lambdas are returned from functions.
>
> The question then becomes, is this kind of unsafety acceptable for a
> built-in lambda facility, or should the compiler support
> closures, which would require much more than just a convenient
> syntax for creating function objects on the fly.

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?

Best,

-- 
Shannon Stewman         | Let us walk through the waning night,
Caught in a whirlpool,  | As dawn-rays tickle our toes, the dew soothes
A quartering act:       | Our blistered soles, and damp bones stir
Solitude or society?    | As crimson cracks under the blue-grey sky.

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