title: Understanding C++0x lambda captures
body: <p>In one of the recent C++0x drafts (n3225.pdf) we can find 5.1.2/10:</p>
  
  <blockquote>
    <p>The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression. An entity (i.e. a variable or this) is said to be explicitly captured if it appears in the lambda-expression’s capture-list.</p>
  </blockquote>
  
  <p>That <em>seems</em> rather restrictive to me. For example, it <em>seems</em> to me that the following things are disallowed:</p>
  
  <pre><code>int global;
  
  struct s {
      int x;
      void memfun() {
          [x,global]{};
      }
  };
  </code></pre>
  
  <p>since <code>x</code> is not necessarily a variable with automatic storage and neither is <code>global</code>. Note that the intention of this capture clause is to let the lambda object store a <em>copy</em> of <code>x</code> and <code>global</code> which might be desirable in case they are changed at a later stage. I am already aware of an alternative:</p>
  
  <pre><code>int global;
  
  struct s {
      int x;
      void memfun() {
          int copyx = x;
          int copyglobal = global;
          [copyx,copyglobal]{};
      }
  };
  </code></pre>
  
  <p>But this boils down to extra copies and additional boiler plate just to capture <code>x</code> and <code>global</code> as copy.</p>
  
  <p>Also, i cannot find anything conclusive in the latest drafts about what happens if we name a local reference in the capture clause:</p>
  
  <pre><code>int main() {
      int  i = 0;
      int &amp;r = i;
      assert([r]{return &amp;r;}() != &amp;i);
  }
  </code></pre>
  
  <p>Does the lambda object "copy a reference" or "copy an int"? If it captures the referred object by copy, this can save us the additional copies from the previous work-around.</p>
  
  <p>GCC apparently supports all these examples and stores a copy of an int in the last case (which is desirable, IMHO). But I would like to know whether this is in fact the intended behaviour according to the C++0x drafts or just a compiler-extension respectivly an implementatin bug.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>templatetypedef pointed out 5.1.2/14 which explains what happens when a reference is named in a capture-clause. As far as I can tell, this allows us to use the following work-around for the first example:</p>
  
  <pre><code>int global;
  
  struct s {
      int x;
      void memfun() {
          auto&amp; cx = x;
          auto&amp; cglob = global;
          [cx,cglob]{};
      }
  };
  </code></pre>
  
  <p>Tia,
  sellibitze</p>