Odd(?) behaviour of a temporary std::ostringstream
<p>I was messing around with <code>std::ostringstream</code> whilst looking at this question: <a href="http://stackoverflow.com/questions/5963242/sprintf-in-c">sprintf in c++ ?</a>, and noticed the <code>stringbuilder()</code> wrapper by Nawaz and thought, well that ought to work with <code>std::ostringstream</code>.</p>

<p>So my first attempt was the following:</p>

<pre><code>std::cout &lt;&lt; (std::ostringstream("select * from foo limit") &lt;&lt; max_limit).str() &lt;&lt; std::endl;
</code></pre>

<p>Now this obviously fails to compile (correctly) as the result of the <code>operator&lt;&lt;</code> is a <code>std::ostream</code> - which doesn't have the member <code>str()</code>. So I thought a cast should do the trick, and specifically a cast to a <code>const</code> reference (works with a cast to a normal reference too), so second attempt:</p>

<pre><code>std::cout &lt;&lt; static_cast&lt;std::ostringstream const&amp;&gt;(std::ostringstream("select * from foo limit") &lt;&lt; max_limit).str() &lt;&lt; std::endl;
</code></pre>

<p>Now this compiles fine and runs, however the output is, well, not what I was expecting.</p>

<blockquote>
  <p>10lect * from foo limit</p>
</blockquote>

<p>Now - here's the question, am I invoking some undefined behaviour somewhere - and if so where? And how is this different to the approach that Nawaz has taken (I guess aside from the result of his operator is the <code>stringbuilder</code> itself rather than <code>std::ostream</code>).</p>

<p>EDIT: here is the <a href="http://www.ideone.com/7gxFo" rel="nofollow">ideone code</a>.</p>

<p>EDIT: oops - forgot to specify, <code>max_limit</code> is <code>int</code>.</p>
