How do capture lists of lambdas actually work in C++11?

前端 未结 1 1515
逝去的感伤
逝去的感伤 2020-12-20 18:33

I know that capture lists make variables available inside a lambda function body like so:

int pos(0);
std::function incPos = [&pos](){ ++po         


        
相关标签:
1条回答
  • 2020-12-20 19:08

    Each lambda expression generates a unique function object (closure) that stores the captured variables as data members. For instance, the lambda expression in your code would be transformed into something like this by the compiler:

    struct __uniquely_named_lambda
    {
      __uniquely_named_lambda(int& pos)
      : pos(pos) {}
      int& pos;
    
      void operator()() const
      { ++pos; }
    };
    

    Invoking the lambda is simply a call to operator().

    The data member is a reference since you captured by reference. If you captured by value it would be a plain int. Also note that generated operator() is const by default. This is why you cannot modify captured variables unless you use the mutable keyword.

    0 讨论(0)
提交回复
热议问题