From -1036690954519817900 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f78e5,a69618ea97f65037 X-Google-Attributes: gidf78e5,public From: Hyman Rosen Subject: Re: nested functions Date: 1998/04/29 Message-ID: <199804281743.NAA18001@calumny.jyacc.com>#1/1 X-Deja-AN: 348618724 Approved: Fergus Henderson References: <6hac23$8lb$1@news2.isdnet.net> <353b85b9.0@news.iprolink.ch> <35459993.3BC581B0@physik.tu-muenchen.de> X-Original-Date: Tue, 28 Apr 1998 13:43:00 -0400 Organization: - X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUANUaZOOEDnX0m9pzZAQFyfgF/aTkXOHfVSNLmh/QxDSczRT7uvs3QwNIh a82GOX31lTtvnN+TZL4nFcq2Nzgf8r4N =Viyl Newsgroups: comp.std.c++ Christopher Eltschka 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. --- [ 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 ]