Life time of an unnamed temporary constructed in if condition expression
<p>How Standard defines the life time of a temporary object constructed during evaluation of an <code>if</code> condition expression?</p>

<p>I looked for this information and found something similar in an example to point [10] in $1.9, page 10. (I'm referring here to Final Draft of the new specification.) Yet still it wasn't clear (enough) for me and since Visual C++ acted differently than my understanding of that example I decided to ask.</p>

<p>Please provide proper references to specification.</p>

<hr>

<p>If you name the object it persists for the entire <code>if</code> (so both <code>true</code> block and <code>false</code> block but is destroyed before <code>if</code> ends).</p>

<p>For example:</p>

<pre><code>if ( MyClass x = f() ) { /* ... */ } else { /* ... */ }
nextInstruction();
</code></pre>

<p><code>x</code> can be used in both <code>if</code> blocks but gets destroyed before <code>nextInstruction</code> gets called.</p>

<p>But what if you don't name it?</p>

<pre><code>if ( f() ) { /* ... */ } else { /* ... */ }
nextInstruction();
</code></pre>

<p>In my understanding of the referenced part of specification the value returned by <code>f()</code> will be destroyed before execution enters one of the blocks (either for <code>true</code> or for <code>false</code>).</p>

<p>However Visual C++ destroys that temporary object as if it was named. <em>(<strong>EDIT:</strong> as Tino Didriksen pointed out Visual C++ does work well here. And indeed now I confirm that as well. I must have made a mistake when looking at initial tests results!)</em></p>

<hr>

<p>This does matter in some edge cases (lets not discuss here how likely they are or whether it is good to write code that way...).</p>

<p>For example lets have:</p>

<pre><code>class ScopedLock {
public:
  ~ScopedLock() { if ( isLocked() ) unlock(); }

  operator bool() const { return isLocked(); }

  /* ... */

};
</code></pre>

<p>Now if we have code like:</p>

<pre><code>if ( ScopedLock lock = resource.lock() ) { /* ... */ }
</code></pre>

<p>we can be sure that when execution enters the <code>true</code> block we own the resource and that it will not be unlocked before we leave that block.</p>

<p>But what if someone wrote it like this:</p>

<pre><code>if ( resource.lock() ) { /* ... */ }
</code></pre>

<p>Now it is crucial at which point the destructor for the temporary <code>ScopedLock</code> will be called. Because it determines whether this code is correct or not (in the sens of resource usage). (Again lets skip discussing whether writing such code is bad in general. That is not the point of this question...)</p>
