From -8952519140824105070
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,a69618ea97f65037
X-Google-Attributes: gidf78e5,public
From: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Subject: Re: nested functions
Date: 1998/04/29
Message-ID: <35472A6D.562EA04C@physik.tu-muenchen.de>#1/1
X-Deja-AN: 348749958
Approved: Fergus Henderson <fjh@cs.mu.oz.au>
Content-Transfer-Encoding: 7bit
References: <6hac23$8lb$1@news2.isdnet.net> <353b85b9.0@news.iprolink.ch> <sfn2dcncm2.fsf@bidra168.bbn.hp.com> <35459993.3BC581B0@physik.tu-muenchen.de> <199804281743.NAA18001@calumny.jyacc.com>
X-Original-Date: Wed, 29 Apr 1998 15:26:05 +0200
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Organization: [posted via] Leibniz-Rechenzentrum, Muenchen (Germany)
X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUANUc4o+EDnX0m9pzZAQFjZAGAljFy/CZVzj/l97KXT8abOfRsAyLxUqPC No/uAu9Pn5Ee/WylLADIJcrKaIVCAbQj =8UUf
Newsgroups: comp.std.c++


Hyman Rosen wrote:
> 
> Christopher Eltschka <celtschk@physik.tu-muenchen.de> writes:
> > Other thanm nested functions, closures would cause problems with the C++
> > object model. Look for example at the following code:
> >
> > struct X { };
> > typedef X* (*fun)();
> > fun f(int i)
> > {
> >   X x;
> >   X* c1() { return &x; }
> >   X* c2() { return 0; }
> >   return i > 0 ? c1 : c2;
> > };
> >
> > Now, when should the destructor of x be called?
> 
> At the normal time, right before f returns. Closures in C and C++ do
> not, and are not meant to, behave like closures in Scheme. C/C++ is
> not a garbage-collected language, and automatic variables do not
> survive the exit of their block. In your example, users of the return
> value of f may will access a dangling pointer. Mot only x, but c1 and
> c2 themselves no longer exist after f returns. Closures in C/C++ are
> still needed for mutually recursive or further nested inner functions,
> however.

But as long as f didn't return, you don't need a closure mechanism,
as the usual nested function mechanism would work well (you could, of
course, define this as a specialized closure, but then you could
as well say C++ already supports nested functions, but limited to
the first level, which is functions at global scope). As I see them,
closures are just there to ensure that variables of the outer scope
survive long enough.
Note that f.ex. Pascal doesn't have closures, but supports nested
functions at arbitrary levels including direct and indirect
recursion. This more than proves that closures are not necessary
for this.
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]



