Lexical Closures for C++

Lexical Closures for C++
复制标题

C 的词法闭包

DOI:
10.1145/512429.512449
复制
发表时间:
1988
影响因子:
6.7
通讯作者:
T. Breuel
T. Breuel
中科院分区:
医学1区
文献类型:
--
作者:
T. Breuel

文献摘要

被引文献

相似文献

我们描述了一个扩展的C++编程语言,允许嵌套的函数定义,并提供了动态生命周期的词法闭包。我们对这个扩展的主要动机是它允许程序员将集合类的迭代器简单地定义为成员函数。这样的迭代器将函数指针或闭包作为参数;提供词法闭包可以让人们自然而容易地表达状态(例如,闭包)。这种技术在Scheme、T或Smalltalk-80等编程语言中很常见,并且可能是在面向对象编程语言中提供泛型迭代构造的最简洁和最自然的方法。嵌套函数定义的能力也鼓励了模块化编程风格。我们希望以这种方式扩展C++语言,而不为闭包引入新的数据类型,也不影响不使用该功能的程序的效率。为了实现这一点,我们建议在创建闭包时,生成一小段代码,加载静态链指针并跳转到函数体。闭包是指向这一小段代码的指针。这个技巧允许我们像对待一个普通的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. We would like to extend the C++ language in this way without introducing new data types for closures and without affecting the efficiency of programs that do not use the feature. In order to achieve this, we propose that when a closure is created, a short segment of code is generated that loads the static chain pointer and jumps to the body of the function. A closure is a pointer to this short segment of code. This trick allows us to treat a closure the same way as a pointer to an ordinary C++ function that does not reference any non-local, non-global variables. We discuss issues of consistency with existing scoping rules, syntax, allocation strategies, portability, and efficiency.