1. 自由变量(free variable)和闭包(closure)
"In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function. "
自由变量指的是相对于函数而言除了函数体内定义的局部变量和参数以外的变量.
“closure is a record storing a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or storage location to which the name was bound when the closure was created.”(Wikipedia)
简而言之,编程语言中的闭包(closure)指的是可引用自由变量的可调用实体(函数,函数指针,函数对象,Lambda表达式等).换句话说,闭包是以下两者的结合:可调用实体,其所引用的自由变量的上下文环境(referencing environment,另一种说法的"状态",state指的是同一个东西).
2. 函数对象
C++11之前不支持闭包,但函数对象可以看作是对于闭包的一种实现(或者说模拟),因为可以利用类的数据成员来保存"状态",例如:
class LessThan{ public: LessThan(int n):s_num(n){} bool operator(int num){return num<s_num;} private: int s_num; }