title: Conditional use of std::lock_guard
body: <p>I have a function where the statement <code>foo</code> should be executed under <code>lock_guard</code> but only when a pointer to a <code>mutex</code> object has been provided to the function as a parameter. Otherwise <code>foo</code> does not have to be <em>protected by  <code>lock_guard</code></em>.</p>
  
  <p>I cannot <em>use</em> the <code>lock_guard</code> within an <code>if</code> because the lock will be released immediately when the <code>if</code> block ends.</p>
  
  <p>so, this code is nonsense:</p>
  
  <pre><code>bar( std::mutex * optionalMutex = nullptr )
  {
     ...
     if ( nullptr != optionalMutex ) {
        std::lock_guard&lt;std::mutex&gt; lockScope( *optionalMutex );
     }          &lt;- Here the lock ends
  
     foo...     &lt;- foo is not protected when optionalMutex was provided
  }
  </code></pre>
  
  <p>I tried something like this:</p>
  
  <pre><code>bar( std::mutex * optionalMutex = nullptr )
  {
     ...
     nullptr == optionalMutex ? 0 : std::lock_guard&lt;std::mutex&gt; lockScope( *optionalMutex );
  
     // this scope should be protected by lock_guard when optionalMutex was provided
  
     foo...
  }
  </code></pre>
  
  <p>More or less, the only one possible solution for me is to repeat  <code>foo</code>:</p>
  
  <pre><code>bar( std::mutex * optionalMutex = nullptr )
  {
     ...
     if ( nullptr != optionalMutex ) {
        std::lock_guard&lt;std::mutex&gt; lockScope( *optionalMutex );
        foo...
     }  else {
        foo...
     }
  }
  </code></pre>
  
  <p>The compiler <code>gcc 4.9.3</code> does not compile the 2nd example and complains: <code>error: expected primary-expression before 'lockScope'</code>. <strong>Update:</strong> Superlokkus explained in his answer why.</p>
  
  <p>But I do want to avoid any code duplicates and therefore also the duplicate <code>foo</code>.</p>
  
  <p><strong>My question:</strong></p>
  
  <p>Is there an <em>elegant</em> way how to implement this problem and <strong>not</strong> to use duplicate <code>foo</code>. I know, I could use a lambda function to <em>group</em> <code>foo</code> but I am curious if there is an another solution.</p>