Lexical Closures for C++
We describe an extension of the C++ programming language that allows the nesting of function definitions and provides lexical closures with dynamic lifetime. Our primary motivation for this extension is that it allows the programmer to define iterators for collection classes simply as member functions. Such iterators take function pointers or closures as arguments; providing lexical closures lets one express state (e.g. accumulators) naturally and easily. This technique is commonplace in programming languages like Scheme, T, or Smalltalk-80, and is probably the most concise and natural way to provide generic iteration constructs in object oriented programming languages. The ability to nest function definitions also encourages a modular programming style.
…
The ability to nest function definitions encourages modular design of programs. It allows the programmer to keep functions and variables that are only used by one function local to that function. In C, such modularity is only possible at the level of files: the scope of the identifier of a function can be limited to a file by declaring it static. The scope of a variable’s identifier that is to be shared among functions must encompass at least a compilation unit since it must be declared at global level. C++ supports limiting the scope of certain kinds of identifiers for functions and variables to member functions by making those functions and variables members of a class.
…
Furthermore, a function defined at global level does not need to be passed a pointer to the lexically enclosing environment, because the lexically enclosing environment is the global environment which is unique and has a known address. These two exceptions together with the fact that C++ allows functions to be defined only at global level make it possible to implement lexical scoping in C++ without using a display, a static link chain, or passing around pointers to environments. Adding space for the static link chain to the activation record of functions that are not defined at the global level is trivial (they can be thought of simply as additional automatic variables). Since the compiler always knows which absolute lexical level an activation record corresponds to, it is not a problem that the activation record for functions at the outermost lexical level diers from that of activation records of functions at other lexical levels.
…
Website: people.debian.org | Filesize: 143kb
No of Page(s): 12
Click here to download Lexical Closures for C++.
Related Tutorial
Tags: Lexical Closures
Comments
Leave a Reply