title: C++11 outer scope variable declared auto
body: <p>In C++ where it's available, it's good practice to use <code>auto</code> for many variables, in particular those whose type is known but annoying to type out:</p>
  
  <pre><code>weird_template_type&lt;int,char&gt;::subtype::recursive_subtype some_function() {
      // ...
  }
  // ...
  auto val = some_function();
  </code></pre>
  
  <p>It's also good to use micro-scopes for RAII objects when that makes sense, e.g. for locking:</p>
  
  <pre><code>some_setup_code();
  int val;
  {
      lock_guard&lt;mutex&gt; lk(mut);
      val = read_shared_memory();
  }
  do_something(val);
  </code></pre>
  
  <p>Is there a way to mix these two idioms, e.g. when your shared-memory-reading code returns a strange type?</p>
  
  <p>The obvious version doesn't work:</p>
  
  <pre><code>auto val;
  {
      lock_guard&lt;mutex&gt; lk(mut);
      val = read_shared_memory();
  }
  do_something(val);
  </code></pre>
  
  <p>This fails at compile time due to an <code>auto</code> variable without an initializer.</p>
  
  <p>Similarly, you can't declare the variable inside the scoped block, or else it isn't available later.</p>
  
  <p>The only immediate options I can see are 1. type out the variable declaration explicitly (bleah), or 2. use <code>auto</code> with some other expression you know to be of the same type (not an improvement). Is there some other way?</p>