Apple Blocks added to C++?

Walter Bright newshound1 at digitalmars.com
Thu Sep 3 02:29:16 PDT 2009


Reimer Behrends wrote:
> The benefit of nested functions is something different. In essence, a 
> nested function allows you to share state with the parent function 
> (absent shared state, there is little reason to not make the nested 
> function a top-level function instead).


The reason for nested functions are:

1. factoring out repeated code within the function into a nested function

2. locality - a nested function is adjacent to where it is used, rather 
than somewhere else

3. isolation - by scope rules, it is easy to see the nested function and 
all calls to it

These may be mundane, but they make for the code being more readable 
than the clumsy workarounds necessary without them. They can also often 
be inlined by the compiler, making them a no-cost abstraction.

> However, nested functions are 
> hidden inside their parent, which means that they are not reusable;

That's actually a feature, see (3).

> on 
> top of that, object-oriented languages already have means to share state 
> between multiple methods (which is sometimes imperfect, but so are 
> nested functions).

Nested classes (Java) and functors (C++) are pretty ugly next to nested 
functions.

One could argue that gcc has them as an extension but nobody uses them. 
My experience with adding extensions to DM C++ is that nobody uses them 
because it is non-standard, not because they are a bad idea.

> So, there are perfectly good reasons to have block closures, but not 
> nested functions. Obviously, there are trade-offs, which may not appeal 
> to everybody, but the design is still a rational one.
> 
> 
>             Reimer Behrends
> 
> 
> [1] http://infoscience.epfl.ch/record/138586



More information about the Digitalmars-d mailing list