title: Lambda: A by-reference capture that could dangle
body: <p>Scott Meyers, in Effective Modern C++, says, at lambda chapter, that:</p>
  
  <p>Consider the following code:</p>
  
  <pre><code>void addDivisorFilter()
  {
      auto calc1 = computeSomeValue1();
      auto calc2 = computeSomeValue2();
  
      auto divisor = computeDivisor(calc1, calc2);
  
      filters.emplace_back(
            [&amp;](int value) { return value % divisor == 0; }
      );
  }
  </code></pre>
  
  <blockquote>
    <p>This code is a problem waiting to happen. The lambda refers to the local variable <code>divisor</code>, but that variable ceases to exist when <code>addDivisorFilter</code> returns. That's immediately after <code>filters.emplace_back</code> returns, so the function that's added to <code>filters</code> is essentially dead on arrival. Using that filter yields undefined behaviour from virtually the moment it's created.</p>
  </blockquote>
  
  <p>The question is: Why is it an undefined behaviour? For what I understand, <code>filters.emplace_back</code> only returns after lambda expression is complete, and, during it execution, <code>divisor</code> is valid.</p>
  
  <p><strong>Update</strong></p>
  
  <p>An important data that I've missed to include is:</p>
  
  <pre><code>using FilterContainer = std::vector&lt;std::function&lt;bool(int)&gt;&gt;;
  FilterContainer filters;
  </code></pre>