- 论坛徽章:
- 5
|
static和闭包的区别,用下面的函数就能看清楚了(用C++11编译):- #include <stdio.h>
- #include <functional>
- int static_f() {
- static int var = 0;
- return ++var;
- }
- std::function<int()> closure_f_gen() {
- int var = 0;
- return [=]() mutable { return ++var; };
- }
- std::function<int()> static_f_gen() {
- return static_f;
- }
- int main(void) {
- auto static_f1 = static_f_gen();
- auto static_f2 = static_f_gen();
- auto closure_f1 = closure_f_gen();
- auto closure_f2 = closure_f_gen();
- printf("static_f: ");
- printf("%d ", static_f1());
- printf("%d ", static_f1());
- printf("%d ", static_f2());
- printf("%d\n", static_f2());
-
- printf("closure_f: ");
- printf("%d ", closure_f1());
- printf("%d ", closure_f1());
- printf("%d ", closure_f2());
- printf("%d\n", closure_f2());
-
- return 0;
- }
复制代码 |
|