title: Static variables in C++ lambdas
body: <p>The following code works fine:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;functional&gt;
  
  std::function&lt;int (void)&gt; get_incrementer() {
      return []() {
          static int count = 0;
          return count++;
      };
  }
  
  int main() {
      using std::cout;
  
      auto incrementer = get_incrementer();
  
      cout &lt;&lt; incrementer() &lt;&lt; std::endl;
      cout &lt;&lt; incrementer() &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  
  <p>But if you capture a local variable by reference instead, it suddenly results in undefined behaviour, presumely because at call-time that location on the stack is being used by something else.</p>
  
  <pre><code>std::function&lt;int (void)&gt; get_incrementer() {
      int count = 0;
  
      return [&amp;count]() {
          return count++;
      };
  }
  </code></pre>
  
  <p>Why does the compiler allow it though? I expected the compiler to either not allow this (it seems trivial to check for this case) or change the storage duration of the local variable.</p>