title: Capturing a static variable by reference in a C++11 lambda
body: <h1>Main question</h1>
  <p>I'm trying to compile the following code with GCC 4.7.2:</p>
  <pre><code>#include &lt;iostream&gt;
  
  int foo() {
      static int bar;
      return [&amp;bar] () { return bar++; } (); // lambda capturing by reference
  }
  
  int main (int argc, char* argv[]) {
      std::cout &lt;&lt; foo() &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  <p>And it seems that is not going well, as the output is this one:</p>
  <pre><code>$p2.cpp: In function ‘int foo()’:
  $p2.cpp:6:14: warning: capture of variable ‘bar’ with non-automatic storage duration [enabled by default]
  $p2.cpp:4:16: note: ‘int bar’ declared here
  </code></pre>
  <p>So, my first question would be:</p>
  <p><strong>Is this a failure of GCC, or the code is not legit C++11? Is this fixed in any recent version of GCC?</strong></p>
  <h1>Using the trick in a shared_ptr factory</h1>
  <p>I consider to build an artifact based on this principle but using a non-literal static variable. This artifact is meant to be a factory of shared_ptr&lt; T &gt; objects, which avoid the creation of new T objects when you just need a duplicate shared_ptr container for the same instance.</p>
  <p>This artifact would look like:</p>
  <pre><code>std::shared_ptr&lt;Foo&gt; create(std::string name) {
      static std::unordered_map&lt;std::string,std::weak_ptr&lt;Foo&gt;&gt; registry;
  
      if (auto it = registry.find(name) != registry.end())
          return registry[name].lock();
  
      auto b = std::shared_ptr&lt;Foo&gt;(
          new Foo(name), 
          [&amp;registry] (Foo* p) {
              registry.erase(p-&gt;getName());
              delete p;
          });
  
      registry.emplace(name,b);
      return b;
  }
  </code></pre>
  <p>As far as I know, if the GCC issue discussed before is not a problem in terms of C++11 conformance, this artifact shouldn't be an issue either. The only thing to take care by using this hack, is to not set the resulting shared_ptr&lt; T &gt; object to any global object which could be destructed after the static variable.</p>
  <p><strong>Am I right about this?</strong></p>