title: Lambda function variables in C++11
body: <p>There are two ways to use lambda function variable:</p>
  
  <pre><code>std::function&lt;int(int, int)&gt; x1 = [=](int a, int b) -&gt; int{return a + b;};
  
  //usage
  void set(std::function&lt;int(int, int)&gt; x);
  std::function&lt;int(int, int)&gt; get();
  </code></pre>
  
  <p>And:</p>
  
  <pre><code>std::function&lt;int(int, int)&gt;* x2 = new std::function&lt;int(int, int)&gt;([=](int a, int b) -&gt; int{return a + b;});
  
  //usage
  void set(std::function&lt;int(int, int)&gt;* x);
  std::function&lt;int(int, int)&gt;* get();
  </code></pre>
  
  <p>I would like to know what are the differences, because I do not know how the lambda function data is stored.</p>
  
  <p>I would like to know the best way in terms of peformance, memory usage and the best way to pass a lambda function as argument or return lambda function.<br>
  I would prefer to use pointers if the size of the lambda function object is bigger than 4 or to avoid errors (if some kind of copy constructor is executed when I do an attribution or if some kind of destructor is executed when I do not want).</p>
  
  <p>How should I declare lambda function variables?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I want to avoid copies and moves, I want to continue to use the same function again.</p>
  
  <p>How should I change this example?</p>
  
  <pre><code>int call1(std::function&lt;int(int, int)&gt; f){
      return f(1, 2);
  }
  int call2(std::function&lt;int(int, int)&gt; f){
      return f(4, 3);
  }
  std::function&lt;int(int, int)&gt;&amp; recv(int s){
      return [=](int a, int b) -&gt; int{return a*b + s;};
  }
  
  int main(){
      std::function&lt;int(int, int)&gt; f1, f2;
  
      f1 = [=](int a, int b) -&gt; int{return a + b;};
      f2 = recv(10);
  
      call1(f1);
      call2(f1);
      call1(f2);
      call2(f2);
  }
  </code></pre>
  
  <p>I cannot return reference in the function recv:</p>
  
  <pre><code> warning: returning reference to temporary
  </code></pre>
  
  <p>Is this a good solution?</p>
  
  <pre><code>int call1(std::function&lt;int(int, int)&gt;* f){
      return (*f)(1, 2);
  }
  int call2(std::function&lt;int(int, int)&gt;* f){
      return (*f)(4, 3);
  }
  
  std::function&lt;int(int, int)&gt;* recv(int s){
      return new std::function&lt;int(int, int)&gt;([=](int a, int b) -&gt; int{return a*b + s;});
  }
  
  int main(){
      std::function&lt;int(int, int)&gt; f1 = [=](int a, int b) -&gt; int{return a + b;};
      std::function&lt;int(int, int)&gt; *f2 = recv(10);
  
      call1(&amp;f1);
      call2(&amp;f1);
      call1(f2);
      call2(f2);
  
      delete f2;
  }
  </code></pre>
  
  <p><strong>EDIT (Conclusion)</strong></p>
  
  <p>A lambda function object is like any object that is instance of a class. The rules for allocation, arguments and attribution are the same.</p>