Advertisement
triclops200

C++11 Closures

Oct 12th, 2012
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <cstdio>
  2. #include <functional>
  3. #include <memory>
  4. int main()
  5. {
  6.     auto fib = []() mutable{
  7.         int j=0,k=1;
  8.         std::shared_ptr<int> aa = std::shared_ptr<int>(new int(j));
  9.         std::shared_ptr<int> bb = std::shared_ptr<int>(new int(k));
  10.         int &a = *aa;
  11.         int &b = *bb;
  12.         a = 0;
  13.         b = 1;
  14.         return [=]() mutable {
  15.             int t = b;
  16.             b = a + b;
  17.             a = t;
  18.             return a;
  19.         };
  20.     };  
  21.     auto f = fib();
  22.     printf("%d %d %d %d\n",f(),f(),f(),f()); // prints: "3 2 1 1" (Right to left function calling in C/C++)
  23.  
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement