Function pointers, Closures, and Lambda

前端 未结 12 1422
臣服心动
臣服心动 2020-11-28 01:51

I am just now learning about function pointers and, as I was reading the K&R chapter on the subject, the first thing that hit me was, \"Hey, this is kinda like a closure

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 02:43

    Closures imply some variable from the point of function definition is bound together with the function logic, like being able to declare a mini-object on the fly.

    One important problem with C and closures is variables allocated on the stack will be destroyed on leaving the current scope, regardless of if a closure was pointing to them. This would lead to the kind of bugs people get when they carelessly return pointers to local variables. Closures basically imply all relevant variables are either ref-counted or garbage-collected items on a heap.

    I'm not comfortable equating lambda with closure because I'm not sure that lambdas in all languages are closures, at times I think lambdas have just been locally defined anonymous functions without the binding of variables (Python pre 2.1?).

提交回复
热议问题