<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Sutter’s Mill</title>
	<atom:link href="http://herbsutter.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://herbsutter.com</link>
	<description>Herb Sutter on software, hardware, and concurrency</description>
	<lastBuildDate>Sat, 25 May 2013 15:30:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='herbsutter.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/4554b8d24c7f200dc5e2e1b18db1893f?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Sutter’s Mill</title>
		<link>http://herbsutter.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://herbsutter.com/osd.xml" title="Sutter’s Mill" />
	<atom:link rel='hub' href='http://herbsutter.com/?pushpress=hub'/>
		<item>
		<title>Lost two comments</title>
		<link>http://herbsutter.com/2013/05/24/lost-two-comments/</link>
		<comments>http://herbsutter.com/2013/05/24/lost-two-comments/#comments</comments>
		<pubDate>Fri, 24 May 2013 19:25:48 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=2012</guid>
		<description><![CDATA[As mentioned in my GotW kickoff post, I&#8217;m experimenting with software and a workflow that lets me maintain a single source document and use it to produce the work in multiple targets, in particular to post to the blog here, to produce print books, and to produce e-books. However, there have been kinks. In particular, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2012&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>As mentioned in my GotW kickoff post, I&#8217;m experimenting with software and a workflow that lets me maintain a single source document and use it to produce the work in multiple targets, in particular to post to the blog here, to produce print books, and to produce e-books.</p>
<p>However, there have been kinks. In particular, on the blog I sometimes repost an update to an already-posted solution, and though it usually correctly updates the existing one, sometimes it chooses to create a new post instead and I have to delete the duplicate. That happened this morning, and I had a remove an accidental duplicate of the GotW #6a solution post.</p>
<p>Unfortunately, people had already left two comments on that duplicate post, and those comments seem to have got lost in the ether. I apologize for that; I think this is the first time I&#8217;ve ever lost someone&#8217;s comment, but it did happen this morning as I&#8217;m still working out kinks in the software. I believe I have a workaround and that it won&#8217;t happen again.</p>
<br />Filed under: <a href='http://herbsutter.com/category/uncategorized/'>Uncategorized</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2012&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/24/lost-two-comments/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #6b: Const-Correctness, Part 2</title>
		<link>http://herbsutter.com/2013/05/24/gotw-6b-const-correctness-part-2/</link>
		<comments>http://herbsutter.com/2013/05/24/gotw-6b-const-correctness-part-2/#comments</comments>
		<pubDate>Fri, 24 May 2013 15:43:05 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=2002</guid>
		<description><![CDATA[const and mutable are powerful tools for writing safer code. Use them consistently. Problem Guru Question In the following code, add or remove const (including minor variants and related keywords) wherever appropriate. Note: Don&#8217;t comment on or change the structure of this program. It&#8217;s contrived and condensed for illustration only. For bonus points: In what [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2002&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>const and mutable are powerful tools for writing safer code. Use them consistently.</em></span>
	</p>
<h1>Problem<br />
</h1>
<h2>Guru Question<br />
</h2>
<p>In the following code, add or remove <span style="color:#2e74b5;">const</span> (including minor variants and related keywords) wherever appropriate. Note: Don&#8217;t comment on or change the structure of this program. It&#8217;s contrived and condensed for illustration only.
</p>
<p>For bonus points: In what places are the program&#8217;s results undefined or uncompilable due to <span style="color:#2e74b5;">const</span> errors?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>class polygon {<br />public:<br />    polygon() : area{-1} {}<br /><br />    void add_point( const point pt ) { area = -1;<br />                                       points.push_back(pt); }<br /><br />    point get_point( const int i ) { return points[i]; }<br /><br />    int get_num_points() { return points.size(); }<br /><br />    double get_area() {<br />        if( area &lt; 0 )   // if not yet calculated and cached<br />            calc_area();     // calculate now<br />        return area;<br />    }<br /><br />private:<br />    void calc_area() {<br />        area = 0;<br />        vector&lt;point&gt;::iterator i;<br />        for( i = begin(points); i != end(points); ++i )<br />            area += /* some work using *i */;<br />    }<br /><br />    vector&lt;point&gt; points;<br />    double        area;<br />};<br /><br />polygon operator+( polygon&amp; lhs, polygon&amp; rhs ) {<br />    auto ret = lhs;<br />    auto last = rhs.get_num_points();<br />    for( auto i = 0; i &lt; last; ++i ) // concatenate<br />        ret.add_point( rhs.get_point(i) );<br />    return ret;<br />}<br /><br />void f( const polygon&amp; poly ) {<br />    const_cast&lt;polygon&amp;&gt;(poly).add_point( {0,0} );<br />}<br /><br />void g( polygon&amp; const poly ) { poly.add_point( {1,1} ); }<br /><br />void h( polygon* const poly ) { poly-&gt;add_point( {2,2} ); }<br /><br />int main() {<br />    polygon poly;<br />    const polygon cpoly;<br /><br />    f(poly);<br />    f(cpoly);<br />    g(poly);<br />    h(&amp;poly);<br />}
</code></pre></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2002&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/24/gotw-6b-const-correctness-part-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #6a Solution: Const-Correctness, Part 1</title>
		<link>http://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/</link>
		<comments>http://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/#comments</comments>
		<pubDate>Fri, 24 May 2013 15:40:37 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=2000</guid>
		<description><![CDATA[const and mutable have been in C++ for many years. How well do you know what they mean today? Problem JG Question 1. What is a &#8220;shared variable&#8221;? Guru Questions 2. What do const and mutable mean on shared variables? 3. How are const and mutable different in C++98 and C++11? Solution 1. What is [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2000&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>const and mutable have been in C++ for many years. How well do you know what they mean today?<br />
</em></span></p>
<h1>Problem</h1>
<h2>JG Question</h2>
<p>1. What is a &#8220;shared variable&#8221;?</p>
<h2>Guru Questions</h2>
<p>2. What do <span style="color:#2e74b5;">const</span> and <span style="color:#2e74b5;">mutable</span> mean on shared variables?</p>
<p>3. How are <span style="color:#2e74b5;">const</span> and <span style="color:#2e74b5;">mutable</span> different in C++98 and C++11?</p>
<h1>Solution</h1>
<h2>1. What is a &#8220;shared variable&#8221;?</h2>
<p>A &#8220;shared variable&#8221; is one that could be accessed from more than one thread at the same time.</p>
<p>This concept is important in the C++ memory model. For example, the C++ memory model (the core of which is described in ISO C++ §1.10) prohibits the invention of a write to a &#8220;potentially shared memory location&#8221; that would not have been written to in a sequentially consistent execution of the program, and the C++ standard library refers to this section when it prohibits &#8220;modify[ing] objects accessible by [other] threads&#8221; through a <span style="color:#2e74b5;">const</span> function, as we will see in #2.</p>
<h2>2. What do const and mutable mean on shared variables?</h2>
<p>Starting with C++11, <span style="color:#2e74b5;">const</span> on a variable that is possibly shared means read-only, safe to read concurrently without external synchronization.</p>
<p>If you perform any operation on a <span style="color:#2e74b5;">const</span> shared variable <span style="color:#2e74b5;">x</span>, or call a <span style="color:#2e74b5;">const</span> member function on <span style="color:#2e74b5;">x</span>, you can assume that operation does not change the observable value of <span style="color:#2e74b5;">x</span>—or even modify the bits of <span style="color:#2e74b5;">x</span> in an observable way even in the presence of concurrency.</p>
<p>If you are implementing a type, unless you know objects of the type can never be shared (which is generally impossible), this means that each of your <span style="color:#2e74b5;">const</span> member functions must be either:</p>
<ul>
<li>truly physically/bitwise <span style="color:#2e74b5;">const</span> with respect to this object; or else</li>
<li>internally synchronized so that if it does perform any actual writes to the object&#8217;s data, that data is correctly protected with a mutex or equivalent (or if appropriate are <span style="color:#2e74b5;">atomic&lt;&gt;</span>) so that any possible concurrent non-<span style="color:#2e74b5;">const</span> accesses by multiple callers can&#8217;t tell the difference.</li>
</ul>
<p>Types that do not respect this cannot be used with the standard library, which requires that:</p>
<blockquote><p>&#8220;… to prevent data races (1.10). … [a] C++ standard library function shall not directly or indirectly modify objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function&#8217;s non-<span style="color:#2e74b5;">const arguments, including this.&#8221;—ISO C++ §17.6.5.9<br />
</span></p></blockquote>
<p>Similarly, writing <span style="color:#2e74b5;">mutable</span> on a member variable means what it has always meant: The variable is &#8220;writable but logically <span style="color:#2e74b5;">const</span>.&#8221; Note what this implies:</p>
<ul>
<li>The &#8220;logically <span style="color:#2e74b5;">const</span>&#8221; part now means &#8220;can be used safely by multiple concurrent <span style="color:#2e74b5;">const</span> operations.&#8221;</li>
<li>The &#8220;<span style="color:#2e74b5;">mutable</span>&#8221; and &#8220;writable&#8221; part further means that some <span style="color:#2e74b5;">const</span> operations may actually be writers of the shared variable, which means it&#8217;s inherently got to be correct to read and write concurrently, so it should be protected with a mutex or similar, or made <span style="color:#2e74b5;">atomic&lt;&gt;</span>.</li>
</ul>
<p>In general, remember:</p>
<blockquote><p><strong>Guideline:</strong> Remember the &#8220;M&amp;M rule&#8221;: For a member variable, <strong>mutable</strong> and <strong>mutex</strong> (or <strong>atomic)</strong> go together.</p></blockquote>
<p>This applies in both directions, to wit:</p>
<blockquote><p><strong>(1) For a member variable, mutable implies mutex (or equivalent):</strong> A <strong>mutable</strong> member variable is presumed to be a mutable shared variable and so must be synchronized internally—protected with a <strong>mutex,</strong> made <strong>atomic,</strong> or similar.</p></blockquote>
<blockquote><p><strong>(2) For a member variable, mutex (or similar synchronization type) implies mutable<span style="color:#2e74b5;">:</span></strong> A member variable that is itself of a synchronization type, such as a <strong>mutex</strong> or a condition variable, naturally wants to be <strong>mutable,</strong> because you will want to use it in a non-<strong>const</strong> way (e.g., take a <strong>std::lock_guard&lt;mutex&gt;</strong>) inside concurrent <strong>const</strong> member functions.</p></blockquote>
<p>We&#8217;ll see an example of (2) in Part 2, GotW #6b.</p>
<h2>3. How are const and mutable different in C++98 and C++11?</h2>
<p>First, let&#8217;s be clear: C++98 single-threaded code still works. C++11 has excellent C++98 compatibility, and even though the meaning of <span style="color:#2e74b5;">const</span> has evolved, C++98 single-threaded code that uses the old &#8220;logically <span style="color:#2e74b5;">const</span>&#8221; meaning of <span style="color:#2e74b5;">const</span> is still valid.</p>
<p>With C++98, we taught a generation of C++ developers that &#8220;<span style="color:#2e74b5;">const</span> means logically <span style="color:#2e74b5;">const</span>, not physically/bitwise <span style="color:#2e74b5;">const</span>.&#8221; That is, in C++98 we taught that <span style="color:#2e74b5;">const</span> meant only that the observable state of the object (say, via its non-private member functions) should not change as far as the caller could tell, but its internal bits might change in order to update counters and instrumentation and other data not accessible via the type&#8217;s public or protected interface.</p>
<p>That definition is not sufficient for concurrency. With C++11 and onward, which now includes a concurrency memory model and thread safety specification for the standard library, this is now much simpler: <span style="color:#2e74b5;">const</span> now really does mean &#8220;read-only, or safe to read concurrently&#8221;—either truly physically/bitwise <span style="color:#2e74b5;">const</span>, or internally synchronized so that any actual writes are synchronized with any possible concurrent non-<span style="color:#2e74b5;">const</span> accesses so the callers can&#8217;t tell the difference.</p>
<p>Although existing C++98-era types still work just fine in C++98-era single-threaded code for compatibility, those types and any new ones you write today should obey the new stricter requirement if they could be used on multiple threads. The good news is that most existing types already followed that rule, and code that relies on casting away <span style="color:#2e74b5;">const</span> and/or using <span style="color:#2e74b5;">mutable</span> data members in single-threaded code has already been generally questionable and relatively rare.</p>
<h2>Summary</h2>
<p>Don&#8217;t shoot yourself (or your fellow programmers) in the foot. Write <span style="color:#2e74b5;">const</span>-correct code.</p>
<p>Using <span style="color:#2e74b5;">const</span> consistently is simply necessary for correctly-synchronized code. That by itself is ample reason to be consistently <span style="color:#2e74b5;">const</span>-correct, but there&#8217;s more: It lets you document interfaces and invariants far more effectively than any mere <span style="color:#2e74b5;">/* I promise not to change this */</span> comment can accomplish. It&#8217;s a powerful part of &#8220;design by contract.&#8221; It helps the compiler to stop you from accidentally writing bad code. It can even help the compiler generate tighter, faster, smaller code. That being the case, there&#8217;s no reason why you shouldn&#8217;t use it as much as possible, and every reason why you should.</p>
<p>Remember that the correct use of <span style="color:#2e74b5;">mutable</span> is a key part of <span style="color:#2e74b5;">const</span>-correctness. If your class contains a member that could change even for <span style="color:#2e74b5;">const</span> objects and operations, make that member <span style="color:#2e74b5;">mutable</span> and protect it with a mutex or make it <span style="color:#2e74b5;">atomic</span>. That way, you will be able to write your class&#8217; <span style="color:#2e74b5;">const</span> member functions easily and correctly, and users of your class will be able to correctly create and use <span style="color:#2e74b5;">const</span> and non-<span style="color:#2e74b5;">const</span> objects of your class&#8217; type.</p>
<p>It&#8217;s true that not all commercial libraries&#8217; interfaces are <span style="color:#2e74b5;">const</span>-correct. That isn&#8217;t an excuse for you to write <span style="color:#2e74b5;">const</span>-incorrect code, though. It is, however, one of the few good excuses to write <span style="color:#2e74b5;">const_cast</span>, plus a detailed comment nearby grumbling about the library vendor&#8217;s laziness and how you&#8217;re looking for a replacement product.</p>
<h2>Acknowledgments</h2>
<p>Thanks in particular to the following for their feedback to improve this article: mttpd, jlehrer.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=2000&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #6a: Const-Correctness, Part 1</title>
		<link>http://herbsutter.com/2013/05/22/gotw-6a-const-correctness-part-1/</link>
		<comments>http://herbsutter.com/2013/05/22/gotw-6a-const-correctness-part-1/#comments</comments>
		<pubDate>Wed, 22 May 2013 19:06:49 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1986</guid>
		<description><![CDATA[const and mutable have been in C++ for many years. How well do you know what they mean today?   Problem JG Question 1. What is a &#8220;shared variable&#8221;? Guru Questions 2. What do const and mutable mean on shared variables? 3. How are const and mutable different in C++98 and C++11? Filed under: GotW<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1986&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>const and mutable have been in C++ for many years. How well do you know what they mean today?<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is a &#8220;shared variable&#8221;?
</p>
<h2>Guru Questions<br />
</h2>
<p>2. What do <span style="color:#2e74b5;">const</span> and <span style="color:#2e74b5;">mutable</span> mean on shared variables?
</p>
<p>3. How are <span style="color:#2e74b5;">const</span> and <span style="color:#2e74b5;">mutable</span> different in C++98 and C++11?</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1986&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/22/gotw-6a-const-correctness-part-1/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #5 Solution: Overriding Virtual Functions</title>
		<link>http://herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/</link>
		<comments>http://herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/#comments</comments>
		<pubDate>Wed, 22 May 2013 19:06:19 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1984</guid>
		<description><![CDATA[Virtual functions are a pretty basic feature, but they occasionally harbor subtleties that trap the unwary. If you can answer questions like this one, then you know virtual functions cold, and you&#8217;re less likely to waste a lot of time debugging problems like the ones illustrated below. Problem JG Question 1. What do the override [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1984&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Virtual functions are a pretty basic feature, but they occasionally harbor subtleties that trap the unwary. If you can answer questions like this one, then you know virtual functions cold, and you&#8217;re less likely to waste a lot of time debugging problems like the ones illustrated below.<br />
</em></span></p>
<h1>Problem</h1>
<h2>JG Question</h2>
<p>1. What do the <span style="color:#2e74b5;">override</span> and <span style="color:#2e74b5;">final</span> keywords do? Why are they useful?</p>
<h2>Guru Question</h2>
<p>2. In your travels through the dusty corners of your company&#8217;s code archives, you come across the following program fragment written by an unknown programmer. The programmer seems to have been experimenting to see how some C++ features worked.</p>
<p style="margin-left:14pt;">(a) What could be improved in the code&#8217;s correctness or style?</p>
<p style="margin-left:14pt;">(b) What did the programmer probably expect the program to print, but what is the actual result?</p>
<pre><code>class base {
public:
    virtual void f( int );
    virtual void f( double );
    virtual void g( int i = 10 );
};

void base::f( int ) {
    cout &lt;&lt; "base::f(int)" &lt;&lt; endl;
}

void base::f( double ) {
    cout &lt;&lt; "base::f(double)" &lt;&lt; endl;
}

void base::g( int i ) {
    cout &lt;&lt; i &lt;&lt; endl;
}

class derived: public base {
public:
    void f( complex&lt;double&gt; );
    void g( int i = 20 );
};

void derived::f( complex&lt;double&gt; ) {
    cout &lt;&lt; "derived::f(complex)" &lt;&lt; endl;
}

void derived::g( int i ) {
    cout &lt;&lt; "derived::g() " &lt;&lt; i &lt;&lt; endl;
}

int main() {
    base    b;
    derived d;
    base*   pb = new derived;

    b.f(1.0);
    d.f(1.0);
    pb-&gt;f(1.0);

    b.g();
    d.g();
    pb-&gt;g();

    delete pb;
}
</code></pre>
<h1>Solution</h1>
<h2>1. What do the override and final keywords do? Why are they useful?</h2>
<p>These keywords give explicit control over virtual function overriding. Writing <span style="color:#2e74b5;">override</span> declares the intent to override a base class virtual function. Writing <span style="color:#2e74b5;">final</span> makes a virtual function no longer overrideable in further-derived classes, or a class no longer permitted to have further-derived classes.</p>
<p>They are useful because they let the programmer explicitly declare intent in a way the language can enforce at compile time. If you write <span style="color:#2e74b5;">override</span> but there is no matching base class function, or you write <span style="color:#2e74b5;">final</span> and a further-derived class tries to implicitly or explicitly override the function anyway, you get a compile-time error.</p>
<p>Of the two, by far the more commonly useful is <span style="color:#2e74b5;">override</span>; uses for <span style="color:#2e74b5;">final</span> are rarer.</p>
<h2>2. (a) What could be improved in the code&#8217;s correctness or style?</h2>
<p>First, let&#8217;s consider some style issues, and one real error:</p>
<h3>1. The code uses explicit new, delete, and an owning *.</h3>
<p>Avoid using owning raw pointers and explicit <span style="color:#2e74b5;">new</span> and <span style="color:#2e74b5;">delete</span> except in rare cases like when you&#8217;re writing the internal implementation details of a low-level data structure.</p>
<pre><code>{
    base*   pb = new derived;

    ...

    delete pb;
}
</code></pre>
<p>Instead of <span style="color:#2e74b5;">new</span> and <span style="color:#2e74b5;">base*</span>, use <span style="color:#2e74b5;">make_unique</span> and <span style="color:#2e74b5;">unique_ptr&lt;base&gt;</span>.</p>
<pre><code>{
    auto pb = unique_ptr&lt;base&gt;{ make_unique&lt;derived&gt;() };

    ...

} // automatic delete here
</code></pre>
<blockquote><p><strong>Guideline:</strong> Don&#8217;t use explicit <strong>new</strong>, <strong>delete</strong>, and owning <strong>*</strong> pointers, except in rare cases encapsulated inside the implementation of a low-level data structure.</p></blockquote>
<p>However, that <span style="color:#2e74b5;">delete</span> brings us to another issue unrelated to how we allocate and manage the lifetime of the object, namely:</p>
<h3>2. base&#8217;s destructor should be virtual or protected.</h3>
<pre><code>class base {
public:
    virtual void f( int );
    virtual void f( double );
    virtual void g( int i = 10 );
};
</code></pre>
<p>This looks innocuous, but the writer of <span style="color:#2e74b5;">base</span> forgot to make the destructor either <span style="color:#2e74b5;">virtual</span> or <span style="color:#2e74b5;">protected</span>. As it is, deleting via a pointer-to-base without a virtual destructor is evil, pure and simple, and corruption is the best thing you can hope for because the wrong destructor will get called, <span style="color:#2e74b5;">derived</span> class members won&#8217;t be destroyed, and <span style="color:#2e74b5;">operator delete</span> will be invoked with the wrong object size.</p>
<blockquote><p><strong>Guideline: </strong>Make base class destructors public and virtual, or protected and nonvirtual.</p></blockquote>
<p>Exactly one of the following can be true for a polymorphic type:</p>
<ul>
<li>Either destruction via a pointer to base is allowed, in which case the function has to be <span style="color:#2e74b5;">public</span> and had better be <span style="color:#2e74b5;">virtual</span>;</li>
<li>or else it isn&#8217;t, in which case the function has to be <span style="color:#2e74b5;">protected</span> (<span style="color:#2e74b5;">private</span> is not allowed because the derived destructor must be able to invoke the base destructor) and would naturally also be nonvirtual (when the derived destructor invokes the base destructor, it does so nonvirtually whether declared <span style="color:#2e74b5;">virtual</span> or not).</li>
</ul>
<h3>Interlude</h3>
<p>For the next few points, it&#8217;s important to differentiate three terms:</p>
<ul>
<li>To <strong>overload</strong> a function <span style="color:#2e74b5;">f</span> means to provide another function with the same name in the same scope but with different parameter types. When <span style="color:#2e74b5;">f</span> is actually called, the compiler will try to pick the best match based on the actual parameters that are supplied.</li>
<li>To <strong>override</strong> a virtual function <span style="color:#2e74b5;">f</span> means to provide another function with the same name and the same parameter types in a derived class.</li>
<li>To <strong>hide</strong> a function <span style="color:#2e74b5;">f</span> that exists in an enclosing scope (base class, outer class, or namespace) means to provide another function with the same name in an inner scope (derived class, nested class, or namespace), which will hide the same function name in an enclosing scope.</li>
</ul>
<h3>3. derived::f is neither an override nor an overload.</h3>
<pre><code>    void derived::f( complex&lt;double&gt; )
</code></pre>
<p><span style="color:#2e74b5;">derived</span> does not overload the <span style="color:#2e74b5;">base::f</span> functions, it hides them. This distinction is very important, because it means that <span style="color:#2e74b5;">base::f(int)</span> and <span style="color:#2e74b5;">base::f(double)</span> are not visible in the scope of <span style="color:#2e74b5;">derived</span>.</p>
<p>If the author of <span style="color:#2e74b5;">derived</span> intended to hide the base functions named <span style="color:#2e74b5;">f</span>, then this is all right. Usually, however, the hiding is inadvertent and surprising, and the correct way to bring the names into the scope of derived is to write the using-declaration <span style="color:#2e74b5;">using base::f;</span> inside <span style="color:#2e74b5;">derived</span>.</p>
<blockquote><p><strong>Guideline: </strong>When providing a non-overridden function with the same name as an inherited function, be sure to bring the inherited functions into scope with a <strong>using</strong>-declaration if you don&#8217;t want to hide them.</p></blockquote>
<h3>4. derived::g overrides base::g but doesn&#8217;t say &#8220;override.&#8221;</h3>
<pre><code>    void g( int i = 20 )  /* override */
</code></pre>
<p>This function overrides the base function, so it should say <span style="color:#2e74b5;">override</span> explicitly. This documents the intent, and lets the compiler tell you if you&#8217;re trying to override something that&#8217;s not virtual or you got the signature wrong by mistake.</p>
<blockquote><p><strong>Guideline: </strong>Always write<strong> override</strong> when you intend to override a virtual function.</p></blockquote>
<h3>5. derived::g overrides base::g but changes the default argument.</h3>
<pre><code>    void g( int i = 20 )
</code></pre>
<p>Changing the default argument is decidedly user-unfriendly. Unless you&#8217;re really out to confuse people, don&#8217;t change the default arguments of the inherited functions you override. Yes, this is legal C++, and yes, the result is well-defined; and no, don&#8217;t do it. Further below, we&#8217;ll see just how confusing this can be.</p>
<blockquote><p><strong>Guideline: </strong>Never change the default arguments of overridden inherited functions.</p></blockquote>
<p>We could go one step further:</p>
<blockquote><p><strong>Guideline:</strong> Avoid default arguments on virtual functions in general.</p></blockquote>
<p>Finally, public virtual functions are great when a class is acting as a pure abstract base class (ABC) that only specifies the virtual interface without implementations, like a C# or Java <span style="color:#2e74b5;">interface</span> does.</p>
<blockquote><p><strong>Guideline:</strong> Prefer to have a class contain only public virtual functions, or no public virtual functions (other than the destructor which is special).</p></blockquote>
<blockquote><p>A pure abstract base class should have only public virtual functions. …</p></blockquote>
<p>But when a class is both providing virtual functions and their implementations, consider the Non-Virtual Interface pattern (NVI) that makes the public interface and the virtual interface separate and distinct.</p>
<blockquote><p>… For any other base class, prefer making public member functions non-virtual, and virtual member functions non-public; the former should have any default arguments and can be implemented in terms of the latter.</p></blockquote>
<p>This cleanly separates the public interface from the derivation interface, lets each follow its natural form best suited for its distinct audience, and avoids having one function exist in tension from doing double duty with two responsibilities. Among other benefits, using NVI will often clarify your class&#8217;s design in important ways, including for example that the default arguments which matter to the caller therefore naturally belong on the public interface, not on the virtual interface. Following this pattern means that several classes of potential problems, including this one of virtuals with default arguments, just naturally don&#8217;t arise.</p>
<p>The C++ standard library follows NVI nearly universally, and other modern OO languages and environments have rediscovered this principle for their own library design guidelines, such as in the .NET <a href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613"><em>Framework Design Guidelines</em></a>.</p>
<h2>2. (b) What did the programmer probably expect the program to print, but what is the actual result?</h2>
<p>Now that we have those issues out of the way, let&#8217;s look at the mainline and see whether it does that the programmer intended:</p>
<pre><code>int main() {
    base    b;
    derived d;
    base*   pb = new derived;

    b.f(1.0);
</code></pre>
<p>No problem. This first call invokes <span style="color:#2e74b5;">base::f( double )</span>, as expected.</p>
<pre><code>    d.f(1.0);
</code></pre>
<p>This calls <span style="color:#2e74b5;">derived::f( complex&lt;double&gt; )</span>. Why? Well, remember that <span style="color:#2e74b5;">derived</span> doesn&#8217;t declare <span style="color:#2e74b5;">using base::f;</span> to bring the base functions named <span style="color:#2e74b5;">f</span> into scope, and so clearly <span style="color:#2e74b5;">base::f( int )</span> and <span style="color:#2e74b5;">base::f( double )</span> can&#8217;t be called. They are not present in the same scope as <span style="color:#2e74b5;">derived::f( complex&lt;double&gt; )</span> so as to participate in overloading.</p>
<p>The programmer may have expected this to call <span style="color:#2e74b5;">base::f( double )</span>, but in this case there won&#8217;t even be a compile error because fortunately(?) <span style="color:#2e74b5;">complex&lt;double&gt;</span> provides an implicit conversion from <span style="color:#2e74b5;">double</span>, and so the compiler interprets this call to mean <span style="color:#2e74b5;">derived::f( complex&lt;double&gt;(1.0) )</span>.</p>
<pre><code>    pb-&gt;f(1.0);
</code></pre>
<p>Interestingly, even though the <span style="color:#2e74b5;">base* pb</span> is pointing to a <span style="color:#2e74b5;">derived</span> object, this calls <span style="color:#2e74b5;">base::f( double )</span> because overload resolution is done on the static type (here <span style="color:#2e74b5;">base</span>), not the dynamic type (here <span style="color:#2e74b5;">derived</span>). You have a <span style="color:#2e74b5;">base</span> pointer, you get the <span style="color:#2e74b5;">base</span> interface.</p>
<p>For the same reason, the call <span style="color:#2e74b5;">pb-&gt;f(complex&lt;double&gt;(1.0));</span> would not compile, because there is no satisfactory function in the base interface.</p>
<pre><code>    b.g();
</code></pre>
<p>This prints <span style="color:#2e74b5;">10</span>, because it simply invokes <span style="color:#2e74b5;">base::g( int )</span> whose parameter defaults to the value <span style="color:#2e74b5;">10</span>. No sweat.</p>
<pre><code>    d.g();
</code></pre>
<p>This prints <span style="color:#2e74b5;">derived::g() 20</span>, because it simply invokes <span style="color:#2e74b5;">derived::g( int )</span> whose parameter defaults to the value <span style="color:#2e74b5;">20</span>. Also no sweat.</p>
<pre><code>    pb-&gt;g();
</code></pre>
<p>This prints <span style="color:#2e74b5;">derived::g() 10</span>.</p>
<p>&#8220;Wait a minute!&#8221; you might protest. &#8220;What&#8217;s going on here?&#8221; This result may temporarily lock your mental brakes and bring you to a screeching halt until you realize that what the compiler has done is quite proper. (Although, of course, the programmer of <span style="color:#2e74b5;">derived</span> ought to be taken out into the back parking lot and yelled at.) The thing to remember is that, like overloads, default parameters are taken from the static type (here <span style="color:#2e74b5;">base</span>) of the object, hence the default value of <span style="color:#2e74b5;">10</span> is taken. However, the function happens to be virtual, and so the function actually called is based on the dynamic type (here <span style="color:#2e74b5;">derived</span>) of the object. Again, this can be avoided by avoiding default arguments on virtual functions, such as by following NVI and avoiding public virtual functions entirely.</p>
<pre><code>    delete pb;
}
</code></pre>
<p>Finally, as noted, this shouldn&#8217;t be needed because you should be using <span style="color:#2e74b5;">unique_ptr</span>s which do the cleanup for you, and <span style="color:#2e74b5;">base</span> should have a virtual destructor so that destruction via any pointer to <span style="color:#2e74b5;">base</span> is correct.</p>
<h2>Acknowledgments</h2>
<p>Thanks in particular to the following for their feedback to improve this article: litb1, KrzaQ, mttpd.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1984&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #5: Overriding Virtual Functions</title>
		<link>http://herbsutter.com/2013/05/20/gotw-5-overriding-virtual-functions/</link>
		<comments>http://herbsutter.com/2013/05/20/gotw-5-overriding-virtual-functions/#comments</comments>
		<pubDate>Mon, 20 May 2013 18:27:25 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1960</guid>
		<description><![CDATA[Virtual functions are a pretty basic feature, but they occasionally harbor subtleties that trap the unwary. If you can answer questions like this one, then you know virtual functions cold, and you&#8217;re less likely to waste a lot of time debugging problems like the ones illustrated below.   Problem JG Question 1. What do the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1960&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Virtual functions are a pretty basic feature, but they occasionally harbor subtleties that trap the unwary. If you can answer questions like this one, then you know virtual functions cold, and you&#8217;re less likely to waste a lot of time debugging problems like the ones illustrated below.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What do the <span style="color:#2e74b5;">override</span> and <span style="color:#2e74b5;">final</span> keywords do? Why are they useful?
</p>
<h2>Guru Question<br />
</h2>
<p>2. In your travels through the dusty corners of your company&#8217;s code archives, you come across the following program fragment written by an unknown programmer. The programmer seems to have been experimenting to see how some C++ features worked.
</p>
<p style="margin-left:14pt;">(a) What could be improved in the code&#8217;s correctness or style?
</p>
<p style="margin-left:14pt;">(b) What did the programmer probably expect the program to print, but what is the actual result?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>class base {<br />public:<br />    virtual void f( int );<br />    virtual void f( double );<br />    virtual void g( int i = 10 );<br />};<br /><br />void base::f( int ) {<br />    cout &lt;&lt; "base::f(int)" &lt;&lt; endl;<br />}<br /><br />void base::f( double ) {<br />    cout &lt;&lt; "base::f(double)" &lt;&lt; endl;<br />}<br /><br />void base::g( int i ) {<br />    cout &lt;&lt; i &lt;&lt; endl;<br />}<br /><br />class derived: public base {<br />public:<br />    void f( complex&lt;double&gt; );<br />    void g( int i = 20 );<br />};<br /><br />void derived::f( complex&lt;double&gt; ) {<br />    cout &lt;&lt; "derived::f(complex)" &lt;&lt; endl;<br />}<br /><br />void derived::g( int i ) {<br />    cout &lt;&lt; "derived::g() " &lt;&lt; i &lt;&lt; endl;<br />}<br /><br />int main() {<br />    base    b;<br />    derived d;<br />    base*   pb = new derived;<br /><br />    b.f(1.0);<br />    d.f(1.0);<br />    pb-&gt;f(1.0);<br /><br />    b.g();<br />    d.g();<br />    pb-&gt;g();<br /><br />    delete pb;<br />}
</code></pre></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1960&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/20/gotw-5-overriding-virtual-functions/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #4 Solution: Class Mechanics</title>
		<link>http://herbsutter.com/2013/05/20/gotw-4-class-mechanics/</link>
		<comments>http://herbsutter.com/2013/05/20/gotw-4-class-mechanics/#comments</comments>
		<pubDate>Mon, 20 May 2013 18:22:22 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1957</guid>
		<description><![CDATA[How good are you at the details of writing classes? This item focuses not only on blatant errors, but even more so on professional style. Understanding these principles will help you to design classes that are easier to use and easier to maintain.   Problem JG Question 1. What makes interfaces &#8220;easy to use correctly, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1957&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>How good are you at the details of writing classes? This item focuses not only on blatant errors, but even more so on professional style. Understanding these principles will help you to design classes that are easier to use and easier to maintain.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What makes interfaces &#8220;easy to use correctly, hard to use incorrectly&#8221;? Explain.
</p>
<h2>Guru Question<br />
</h2>
<p>2. You are doing a code review. A programmer has written the following class, which shows some poor style and has some real errors. How many can you find, and how would you fix them?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>class complex {<br />public:<br />    complex( double r, double i = 0 )<br />        : real(r), imag(i)<br />    { }<br /><br />    void operator+ ( complex other ) {<br />        real = real + other.real;<br />        imag = imag + other.imag;<br />    }<br /><br />    void operator&lt;&lt;( ostream os ) {<br />        os &lt;&lt; "(" &lt;&lt; real &lt;&lt; "," &lt;&lt; imag &lt;&lt; ")";<br />    }<br /><br />    complex operator++() {<br />        ++real;<br />        return *this;<br />    }<br /><br />    complex operator++( int ) {<br />        auto temp = *this;<br />        ++real;<br />        return temp;<br />    }<br /><br />    // ... more functions that complement the above ...<br /><br />private:<br />    double real, imag;<br />};
</code></pre>
</p>
<p>Note: This is not intended to be a complete class. For example, if you provide <span style="color:#2e74b5;">operator++</span> you would normally also provide <span style="color:#2e74b5;">operator&#8211;</span>. Rather, this is an instructive example to focus on the mechanics of writing correctly the kinds of functions this class is trying to support.
</p>
<p>
 </p>
<h1>Solution<br />
</h1>
<h2>1. What makes interfaces &#8220;easy to use correctly, hard to use incorrectly&#8221;? Explain.<br />
</h2>
<p>We want to enable a <a href="http://blogs.msdn.com/b/brada/archive/2003/10/02/50420.aspx">&#8220;pit of success&#8221;</a> where users of our type just naturally fall into good practices—they just naturally write code that is valid, correct, and efficient.
</p>
<p>On the other hand, we want to make it hard for our users to get into trouble—we want code that would be incorrect or inefficient to be invalid (a compile time error if possible) or at least inconvenient and hard to write silently so that we can protect the user from unwelcome surprises.
</p>
<p>Scott Meyers <a href="http://programmer.97things.oreilly.com/wiki/index.php/Make_Interfaces_Easy_to_Use_Correctly_and_Hard_to_Use_Incorrectly">popularized</a> this guidance. See his concise writeup for further examples.
</p>
<p>
 </p>
<h2>2. You are doing a code review. A programmer has written the following class, which shows some poor style and has some real errors. How many can you find, and how would you fix them?<br />
</h2>
<p>This class has a lot of problems—even more than I will show explicitly here. The point of this puzzle was primarily to highlight class mechanics (issues like &#8220;what is the canonical form of <span style="color:#2e74b5;">operator&lt;&lt;</span>?&#8221; and &#8220;should <span style="color:#2e74b5;">operator+</span> be a member?&#8221;) rather than point out where the interface is just plain poorly designed. However, I will start off with perhaps the two most useful observation first:
</p>
<p>First, this is a code review but the developer doesn&#8217;t seem to have tried to even unit-test his code, else he would have found some glaring problems.
</p>
<p>Second, why write a <span style="color:#2e74b5;">complex</span> class when one already exists in the standard library? And, what&#8217;s more, when the standard one isn&#8217;t plagued with any of the following problems and has been crafted based on years of practice by the best people in our industry? Humble thyself and reuse.
</p>
<blockquote><p><strong>Guideline:</strong> Reuse code—especially standard library code—instead of handcrafting your own. It&#8217;s faster, easier, and safer.
</p>
</blockquote>
<p>Perhaps the best way to fix the problems in the <span style="color:#2e74b5;">complex</span> code is to avoid using the class at all, and use the <span style="color:#2e74b5;">std::complex</span> template instead.
</p>
<p>Having said that, it&#8217;s an instructive example, so let&#8217;s go through the class as written and fix the problems as we go. First, the constructor:
</p>
<h3>1. The default constructor is missing.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    complex( double r, double i = 0 )<br />        : real(r), imag(i)<br />    { }
</code></pre>
</p>
<p>Once we supply a user-written constructor, we suppress the implicit generation of the default constructor. Beyond &#8220;easy to use correctly,&#8221; not having a default constructor makes the class annoying to use at all. In this case, we could either default both parameters, or provide a <span style="color:#2e74b5;">complex() = default;</span> and declare the data members with initializers such as <span style="color:#2e74b5;">double real = 0, imag = 0;</span> , or just delegate with <span style="color:#2e74b5;">complex() : complex(0) { }</span> . Just defaulting the parameter is the simplest here.
</p>
<p>Also, as explained in GotW #1, prefer to use <span style="color:#2e74b5;">{ }</span> consistently for initialization rather than <span style="color:#2e74b5;">( )</span> just as a good modern habit. The two mean exactly the same thing in this case, but <span style="color:#2e74b5;">{ }</span> lets us be more consistent, and could catch a few errors during maintenance, such as typos that would invoke <span style="color:#2e74b5;">double</span>-to-<span style="color:#2e74b5;">float</span> narrowing conversions.
</p>
<h3>2. operator+ passes by value.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    void operator+ ( complex other ) {<br />        real = real + other.real;<br />        imag = imag + other.imag;<br />    }
</code></pre>
</p>
<p>Although we&#8217;re about make other changes to this function in a moment, as written this parameter should be passed by <span style="color:#2e74b5;">const&amp;</span> because all we do is read from it.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer passing a read-only parameter by <strong>const&amp;</strong> if you are only going to read from it (not make a copy of it).
</p>
</blockquote>
<h3>3. operator+ modifies this object&#8217;s value.<br />
</h3>
<p>Instead of returning <span style="color:#2e74b5;">void</span>, <span style="color:#2e74b5;">operator+</span> should return a <span style="color:#2e74b5;">complex</span> containing the sum and not modify this object&#8217;s value. Users who write <span style="color:#2e74b5;">val1 + val2</span> and see <span style="color:#2e74b5;">val1</span> changed are unlikely to be impressed by these gratuitously weird semantics. As Scott Meyers is wont to say, when writing a value type, &#8220;do as the <span style="color:#2e74b5;">int</span>s do&#8221; and follow the conventions of the built-in types.
</p>
<h3>4. operator+ is not written in terms of operator+= (which is missing).<br />
</h3>
<p>Really, this <span style="color:#2e74b5;">operator+</span> is trying to be <span style="color:#2e74b5;">operator+=</span>. It should be split into an actual <span style="color:#2e74b5;">operator+</span> and <span style="color:#2e74b5;">operator+=</span>, with the former calling the latter.
</p>
<blockquote><p><strong>Guideline: </strong>If you supply a standalone version of an operator (e.g., <strong>operator+</strong>), always supply an assignment version of the same operator (e.g., <strong>operator+=</strong>) and prefer implementing the former in terms of the latter. Also, always preserve the natural relationship between op and op= (where op stands for any operator).
</p>
</blockquote>
<p>Having <span style="color:#2e74b5;">+=</span> is good, because users should prefer using it. Even in the above code, <span style="color:#2e74b5;">real = real + other.real;</span> should be <span style="color:#2e74b5;">real += other.real;</span> and similarly for the second line.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer writing <strong>a op= b</strong> instead of <strong>a = a op b</strong> (where op stands for any operator). It&#8217;s clearer, and it&#8217;s often more efficient.
</p>
</blockquote>
<p>The reason why <span style="color:#2e74b5;">operator+=</span> is more efficient is that it operates on the left-hand object directly and returns only a reference, not a temporary object. On the other hand, <span style="color:#2e74b5;">operator+</span> must return a temporary object. To see why, consider the following canonical forms for how <span style="color:#2e74b5;">operator+=</span> and <span style="color:#2e74b5;">operator+</span> should normally be implemented for some type <span style="color:#2e74b5;">T</span>.
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>T&amp; T::operator+=( const T&amp; other ) {<br />    //...<br />    return *this;<br />}<br /><br />T operator+( T a, const T&amp; b ) {<br />    a += b;<br />    return a;<br />}
</code></pre>
</p>
<p>Did you notice that one parameter is passed by value, and one by reference? That&#8217;s because if you&#8217;re going to copy from a parameter anyway, it&#8217;s often better to pass it by value, which will naturally enable a move operation if the caller passes a temporary object such as in expressions like <span style="color:#2e74b5;">(val1 * val2) + val3</span>. This is a good habit to follow even in cases like <span style="color:#2e74b5;">complex</span> where a move is the same cost as a copy, since it doesn&#8217;t cost any efficiency when move and copy are the same, and arguably makes for cleaner code than passing by reference and adding an extra named local object. We&#8217;ll see more on parameter passing in a future GotW.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer passing a read-only parameter by value if you&#8217;re going to make a copy of the parameter anyway, because it enables move from rvalue arguments.
</p>
</blockquote>
<p>Implementing <span style="color:#2e74b5;">+</span> in terms of <span style="color:#2e74b5;">+=</span> both makes the code simpler and guarantees consistent semantics as the two functions are less likely to diverge during maintenance.
</p>
<h3>5. operator+ should not be a member function.<br />
</h3>
<p>If <span style="color:#2e74b5;">operator+</span> is made a member function, as it is here, then it won&#8217;t work as naturally as your users may expect when you do decide to allow implicit conversions from other types. Here, an implicit conversion from <span style="color:#2e74b5;">double</span> to <span style="color:#2e74b5;">complex</span> makes sense, but with the original class users have an asymmetry: Specifically, when adding <span style="color:#2e74b5;">complex</span> objects to numeric values, you can write <span style="color:#2e74b5;">a = b + 1.0</span> but not <span style="color:#2e74b5;">a = 1.0 + b</span> because a member <span style="color:#2e74b5;">operator+</span> requires a <span style="color:#2e74b5;">complex</span> (and not a <span style="color:#2e74b5;">double</span>) as its left-hand argument.
</p>
<p>Finally, the other reason to prefer non-members is because they provide better encapsulation, as <a href="http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197">pointed out by Scott Meyers</a>.
</p>
<blockquote><p><strong>Guideline: </strong>Prefer these guidelines for making an operator a member vs. nonmember function: unary operators are members; <strong>= () []</strong> and <strong>-&gt;</strong> must be members; the assignment operators (<strong>+= –= /= *=</strong> etc.) must be members; all other binary operators are nonmembers.
</p>
</blockquote>
<h3>6. operator&lt;&lt; should not be a member function.<br />
</h3>
<p>The author of this code didn&#8217;t really mean to enable the syntax <span style="color:#2e74b5;">my_complex &lt;&lt; cout</span>, did they?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    void operator&lt;&lt;( ostream os ) {<br />        os &lt;&lt; "(" &lt;&lt; real &lt;&lt; "," &lt;&lt; imag &lt;&lt; ")";<br />    }
</code></pre>
</p>
<p>The same reasons already given to show why <span style="color:#2e74b5;">operator+</span> should be a nonmember apply also to <span style="color:#2e74b5;">operator&lt;&lt;</span>, only more so because a member the first parameter has to be a stream, not a <span style="color:#2e74b5;">complex</span>. Further, the parameters should be references: <span style="color:#2e74b5;">(ostream&amp;, const complex &amp;)</span>.
</p>
<p>Note also that the nonmember <span style="color:#2e74b5;">operator&lt;&lt;</span> should normally be implemented in terms of a(n often virtual) <span style="color:#2e74b5;">const</span> member function that does the work, usually named something like <span style="color:#2e74b5;">print</span>.
</p>
<h3>7. operator&lt;&lt; should return ostream&amp;.<br />
</h3>
<p>Further, <span style="color:#2e74b5;">operator&lt;&lt;</span> should have a return type of <span style="color:#2e74b5;">ostream&amp;</span> and should return a reference to the stream in order to permit chaining. That way, users can use your <span style="color:#2e74b5;">operator&lt;&lt;</span> naturally in code like <span style="color:#2e74b5;">cout &lt;&lt; a &lt;&lt; b;</span>.
</p>
<blockquote><p><strong>Guideline: </strong>Always return stream references from <strong>operator&lt;&lt;</strong> and <strong>operator&gt;&gt;</strong>.
</p>
</blockquote>
<h3>8. The preincrement operator&#8217;s return type is incorrect.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    complex operator++() {<br />        ++real;<br />        return *this;<br />    }
</code></pre>
</p>
<p>Ignoring for the sake of argument whether preincrement is meaningful for <span style="color:#2e74b5;">complex</span> numbers, if the function exists it should return a reference. This lets client code operate more intuitively and avoids needless inefficiency.
</p>
<blockquote><p><strong>Guideline: </strong>When you <strong>return *this</strong>, the return type should usually be a reference.
</p>
</blockquote>
<h3>9. Postincrement should be implemented in terms of preincrement.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    complex operator++( int ) {<br />        auto temp = *this;<br />        ++real;<br />        return temp;<br />    }
</code></pre>
</p>
<p>Instead of repeating the work, prefer to call <span style="color:#2e74b5;">++*this</span>. See GotW #2 for the full canonical form for postincrement.
</p>
<blockquote><p><strong>Guideline: </strong>For consistency, always implement postincrement in terms of preincrement, otherwise your users will get surprising (and often unpleasant) results.
</p>
</blockquote>
<h3>Summary<br />
</h3>
<p>That&#8217;s it. There are other modern C++ features we could apply here, but they would be arguably gratuitous and not appropriate for general recommendations. For example, this is a value type not designed to be inherited from, so we could prevent inheritance by making the class <span style="color:#2e74b5;">final</span>, but that would be protecting against Machiavelli, not Murphy, and there&#8217;s no need for a general guideline that tells everyone they should now write <span style="color:#2e74b5;">final</span> on every value type; that would just be tedious and unnecessary.
</p>
<p>Here&#8217;s a corrected version of the class, ignoring design and style issues not explicitly noted above:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>class complex {<br />public:<br />    complex( double r = 0, double i = 0 )<br />        : real{r}, imag{i}<br />    { }<br /><br />    complex&amp; operator+=( const complex&amp; other ) {<br />        real += other.real;<br />        imag += other.imag;<br />        return *this;<br />    }<br /><br />    complex&amp; operator++() {<br />        ++real;<br />        return *this;<br />    }<br /><br />    complex operator++( int ) {<br />        auto temp = *this;<br />        ++*this;<br />        return temp;<br />    }<br /><br />    ostream&amp; print( ostream&amp; os ) const {<br />        return os &lt;&lt; "(" &lt;&lt; real &lt;&lt; "," &lt;&lt; imag &lt;&lt; ")";<br />    }<br /><br />private:<br />    double real, imag;<br />};<br /><br />complex operator+( complex lhs, const complex&amp; rhs ) {<br />    lhs += rhs;<br />    return lhs;<br />}<br /><br />ostream&amp; operator&lt;&lt;( ostream&amp; os, const complex&amp; c ) {<br />    return c.print(os);<br />}
</code></pre>
</p>
<h2>Acknowledgments<br />
</h2>
<p>Thanks in particular to the following for their feedback to improve this article: Mikhail Belyaev, jlehrer, Olaf van der Spek, Marshall, litb1, hm, Dave Harris, nosenseetal.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1957&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/20/gotw-4-class-mechanics/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #4: Class Mechanics (7/10)</title>
		<link>http://herbsutter.com/2013/05/16/gotw-4-class-mechanics-710/</link>
		<comments>http://herbsutter.com/2013/05/16/gotw-4-class-mechanics-710/#comments</comments>
		<pubDate>Thu, 16 May 2013 20:09:32 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1920</guid>
		<description><![CDATA[How good are you at the details of writing classes? This item focuses not only on blatant errors, but even more so on professional style. Understanding these principles will help you to design classes that are easier to use and easier to maintain.   Problem JG Question 1. What makes interfaces &#8220;easy to use correctly, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1920&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>How good are you at the details of writing classes? This item focuses not only on blatant errors, but even more so on professional style. Understanding these principles will help you to design classes that are easier to use and easier to maintain.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What makes interfaces &#8220;easy to use correctly, hard to use incorrectly&#8221;? Explain.
</p>
<h2>Guru Question<br />
</h2>
<p>2. You are doing a code review. A programmer has written the following class, which shows some poor style and has some real errors. How many can you find, and how would you fix them?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>class complex {<br />public:<br />    complex( double r, double i = 0 )<br />        : real(r), imag(i)<br />    { }<br /><br />    void operator+ ( complex other ) {<br />        real = real + other.real;<br />        imag = imag + other.imag;<br />    }<br /><br />    void operator&lt;&lt;( ostream os ) {<br />        os &lt;&lt; "(" &lt;&lt; real &lt;&lt; "," &lt;&lt; imag &lt;&lt; ")";<br />    }<br /><br />    complex operator++() {<br />        ++real;<br />        return *this;<br />    }<br /><br />    complex operator++( int ) {<br />        auto temp = *this;<br />        ++real;<br />        return temp;<br />    }<br /><br />    // ... more functions that complement the above ...<br /><br />private:<br />    double real, imag;<br />};
</code></pre>
</p>
<p>Note: This is not intended to be a complete class. For example, if you provide <span style="color:#2e74b5;">operator++</span> you would normally also provide <span style="color:#2e74b5;">operator&#8211;</span>. Rather, this is an instructive example to focus on the mechanics of writing correctly the kinds of functions this class is trying to support.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1920&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/16/gotw-4-class-mechanics-710/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #3 Solution: Using the Standard Library (or, Temporaries Revisited)</title>
		<link>http://herbsutter.com/2013/05/16/gotw-3-solution-using-the-standard-library-or-temporaries-revisited/</link>
		<comments>http://herbsutter.com/2013/05/16/gotw-3-solution-using-the-standard-library-or-temporaries-revisited/#comments</comments>
		<pubDate>Thu, 16 May 2013 19:58:23 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1912</guid>
		<description><![CDATA[Effective reuse is an important part of good software engineering. To demonstrate how much better off you can be by using standard library algorithms instead of handcrafting your own, let&#8217;s reconsider the previous question to demonstrate how many of the problems could have been avoided by simply reusing what&#8217;s already available in the standard library. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1912&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Effective reuse is an important part of good software engineering. To demonstrate how much better off you can be by using standard library algorithms instead of handcrafting your own, let&#8217;s reconsider the previous question to demonstrate how many of the problems could have been avoided by simply reusing what&#8217;s already available in the standard library.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is the most widely used C++ library?
</p>
<h2>Guru Question<br />
</h2>
<p>2. How many of the pitfalls in GotW #2 could have been avoided in the first place, if only the programmer had replaced the explicit iterator-based <span style="color:#2e74b5;">for</span> loop with:
</p>
<p style="margin-left:36pt;">(a) a range-based <span style="color:#2e74b5;">for</span> loop?
</p>
<p style="margin-left:36pt;">(b) a standard library algorithm call?
</p>
<p>Demonstrate. (Note: As with GotW #2, don&#8217;t change the semantics of the function, even though they could be improved.)
</p>
<p>To recap, here is the mostly-fixed function:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( const list&lt;employee&gt;&amp; emps, const string&amp; name ) {<br />    for( auto i = begin(emps);  i != end(emps); ++i ) {<br />        if( i-&gt;name() == name ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    return "";<br />}
</code></pre>
</p>
<p>
 </p>
<h1>Solution<br />
</h1>
<h2>1. What is the most widely used C++ library?<br />
</h2>
<p>The C++ standard library, with its implementations on every platform.
</p>
<p>
 </p>
<h2>2. (a) How many of the pitfalls in GotW #2 could have been avoided with a range-based for loop?<br />
</h2>
<p>Astute readers of GotW #2 will have been champing at the bit to say: &#8220;Why aren&#8217;t you using a range-based <span style="color:#2e74b5;">for</span> loop?&#8221; Indeed, why not? That would solve several of the temporaries, never mind be easier to write.
</p>
<p>Compare the original unimproved explicit iterator loop:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    for( auto i = begin(emps); i != end(emps); i++ ) {<br />        if( *i == name ) {<br />            return i-&gt;addr;<br />        }<br />    }
</code></pre>
</p>
<p>with the range-based <span style="color:#2e74b5;">for</span> loop (bonus points if you remembered to write the <span style="color:#2e74b5;">const auto&amp;</span>):
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    for( const auto&amp; e : emps ) {<br />        if( e == name ) {<br />            return e.addr;<br />        }<br />    }
</code></pre>
</p>
<p>The expressions <span style="color:#2e74b5;">e == name</span> and <span style="color:#2e74b5;">return e.addr;</span> are unchanged in terms of their possible or actual temporaries. But the questions in the naked loop code about whether or not the <span style="color:#2e74b5;">=</span> causes a temporary (recall: it doesn&#8217;t), whether or not <span style="color:#2e74b5;">end()</span> recalculation matters and should be hoisted (recall: probably not, but maybe), and whether or not <span style="color:#2e74b5;">i++</span> should be rewritten <span style="color:#2e74b5;">++i</span> (recall: it should) all simply don&#8217;t arise in the range-<span style="color:#2e74b5;">for</span> code. Such is the power of clear code, and using a higher level of abstraction.
</p>
<p>A key advantage is that using the range-based <span style="color:#2e74b5;">for</span> loop has increased our level of abstraction, the information density in our code. Consider: What can you say about the following two pieces of code without reading what comes next?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    for( auto i = begin(emps); i != end(emps); i++ ) {   // A<br /><br />    for( const auto&amp; e : emps ) {                        // B
</code></pre>
</p>
<p>At first it might seem that lines A and B convey the same information, but they don&#8217;t. When you see A, all you know is that there&#8217;s a loop of some sort that uses an iterator over <span style="color:#2e74b5;">emps</span>. Granted, we&#8217;re so used to A that our eye&#8217;s peripheral vision tends to &#8220;autocomplete&#8221; it in our heads into &#8220;a loop that visits the elements of <span style="color:#2e74b5;">emps</span> in order&#8221; and our autocomplete is often correct—except when it isn&#8217;t: was that a <span style="color:#2e74b5;">++</span>, or a s<span style="color:#2e74b5;">+= 2</span> in a strided loop? is the index modified inside the body? Our peripheral vision might be wrong.
</p>
<p>On the other hand, B conveys more information to the reader. When you see B, you know for certain without inspecting the body of the loop that it is a loop that visits the element of <span style="color:#2e74b5;">emps</span> in order. What&#8217;s more, you&#8217;ve simplified the loop control because there&#8217;s no need for an iterator indirection. Both of these are raising the level of abstraction of our code, and that&#8217;s a good thing.
</p>
<p>Note that, as discussed in GotW #2, the naked <span style="color:#2e74b5;">for</span> loop didn&#8217;t naturally allow consolidating to a single <span style="color:#2e74b5;">return</span> statement without resorting to making the code more complex by adding an additional variable and performing extra computation (a default construction followed by an assignment, instead of just a construction). That&#8217;s still true of the range-based <span style="color:#2e74b5;">for</span> loop form, because it still has the two <span style="color:#2e74b5;">return</span> statements in different scopes.
</p>
<h2>2. (b) … with a standard library algorithm call?<br />
</h2>
<p>With no other changes, simply using the standard <span style="color:#2e74b5;">find</span> algorithm could do everything the range-based <span style="color:#2e74b5;">for</span> loop did to avoid needless temporaries (and questions about them):
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>// Better (focusing on internals)<br />//<br />string find_addr( /*...*/ ) {<br />    const auto i = find( begin(emps), end(emps), name );   // TFTFY<br />    return i != end(emps) ? i-&gt;addr : "";<br />}
</code></pre>
</p>
<p>This naturally eliminates the same temporaries as the range-<span style="color:#2e74b5;">for</span> version, and it further increases our level of abstraction. As with the range-based <span style="color:#2e74b5;">for</span> loop, we can see at a glance and for certain that the loop will visit the elements of <span style="color:#2e74b5;">emps</span> in order, but on top of that we also know we&#8217;re trying to <span style="color:#2e74b5;">find</span> something and will get back an iterator to the first matching element if one exists. We do still have an iterator indirection, but only a single-use iterator object and no iterator arithmetic as in the original naked iterator <span style="color:#2e74b5;">for</span> loop.
</p>
<p>Further, we have eliminated a loop nested scope entirely and flattened out the function to a single scope which can simplify this calling function in ways even the range-<span style="color:#2e74b5;">for</span> couldn&#8217;t. To demonstrate still more just how fundamental this point is, note that what else the flattening out of the body buys us: Now, because the <span style="color:#2e74b5;">return</span> statements are in the same scope (possible only because we eliminated the loop scope), we have the option of naturally combining them. You could still write <span style="color:#2e74b5;">if( i != end(emps) ) return i-&gt;addr; else return &#8220;&#8221;;</span> here, on one or two or four lines, but there&#8217;s no need to. To be clear, the point here is not that reducing <span style="color:#2e74b5;">return</span> statements should be a goal in itself—it shouldn&#8217;t be, and &#8220;single exit&#8221; thinking has always been flawed as we already saw in GotW #2. Rather, the point is that using an algorithm often simplifies our code more than an explicit loop, even a range-<span style="color:#2e74b5;">for</span> loop, can do—not only directly by removing extra indirections and extra variables and a loop nested scope, but often also by permitting additional simplifications in nearby code.
</p>
<p>The above code might still cause a temporary when comparing an <span style="color:#2e74b5;">employee</span> with a <span style="color:#2e74b5;">string</span>, and we can eliminate even that temporary if we go one small step further and use <span style="color:#2e74b5;">find_if</span> with a custom comparison that compares <span style="color:#2e74b5;">e.name() == name</span> to avoid a possible conversion, assuming something like a suitable <span style="color:#2e74b5;">employee::name()</span> is available as we did in GotW #2. Combining this with the other fixes to pass parameters by reference, we get:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>// Better still (complete)<br />//<br />string find_addr( const list&lt;employee&gt;&amp; emps, const string&amp; name ) {<br />    const auto i = find_if( begin(emps), end(emps),<br />                      [&amp;](const auto&amp; e) { return e.name() == name; } );<br />    return i != end(emps) ? i-&gt;addr : "";<br />}
</code></pre>
</p>
<p>
 </p>
<h2>Summary<br />
</h2>
<p>Prefer algorithm calls over explicit loops, when you have or can write a suitable algorithm that does what you want. They raise the level of abstraction and the clarity of our code. Scott Meyers&#8217; advice in <em>Effective STL</em> is still true, and more applicable than even now that lambdas make algorithms much more usable than before:
</p>
<blockquote><p><strong>Guideline: </strong>Prefer algorithm calls to explicit loops. Algorithm calls are often clearer and reduce complexity. If no suitable algorithm exists, why not write it? You&#8217;ll use it again.
</p>
</blockquote>
<p>Prefer reusing existing library code to handcrafting your own. The more widely used the library, the more likely it is to come well-designed, pre-debugged, and pre-optimized for many common requirements. And what library is more widely used than the standard library? In your C++ program, your standard library implementation is the most widely used library code you&#8217;re likely to use. This helps you both in the library&#8217;s design and its implementation: It&#8217;s full of code that&#8217;s intended to be used and reused, and to that end a lot of thought and care has gone into the design of its features, including its standard algorithms like <span style="color:#2e74b5;">find</span> and <span style="color:#2e74b5;">sort</span>. Implementers have also spent hours sweating over efficiency details, and usability details, and all sorts of other considerations so that you don&#8217;t have to—including performing optimizations you should almost never resort to in application-level code, such as using nonportable OS- and CPU-target specific optimizations.
</p>
<p>So, always prefer to reuse code, especially algorithms and especially the standard library, and escape the trap of &#8220;I&#8217;ll-write-my-own-just-&#8217;cause-I-can.&#8221;
</p>
<blockquote><p><strong>Guideline: </strong>Reuse code—especially standard library code—instead of handcrafting your own. It&#8217;s faster, easier, and safer.
</p>
</blockquote>
<h2>Acknowledgments<br />
</h2>
<p>Thanks in particular to the following for their feedback to improve this article: Olaf ven der Spek, Sam Kramer.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1912&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/16/gotw-3-solution-using-the-standard-library-or-temporaries-revisited/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #3: Using the Standard Library (or, Temporaries Revisited) (3/10)</title>
		<link>http://herbsutter.com/2013/05/13/gotw-3-using-the-standard-library-or-temporaries-revisited-310/</link>
		<comments>http://herbsutter.com/2013/05/13/gotw-3-using-the-standard-library-or-temporaries-revisited-310/#comments</comments>
		<pubDate>Mon, 13 May 2013 12:31:55 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1888</guid>
		<description><![CDATA[Effective reuse is an important part of good software engineering. To demonstrate how much better off you can be by using standard library algorithms instead of handcrafting your own, let&#8217;s reconsider the previous question to demonstrate how many of the problems could have been avoided by simply reusing what&#8217;s already available in the standard library. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1888&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Effective reuse is an important part of good software engineering. To demonstrate how much better off you can be by using standard library algorithms instead of handcrafting your own, let&#8217;s reconsider the previous question to demonstrate how many of the problems could have been avoided by simply reusing what&#8217;s already available in the standard library.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is the most widely used C++ library?
</p>
<h2>Guru Question<br />
</h2>
<p>2. How many of the pitfalls in GotW #2 could have been avoided in the first place, if only the programmer had replaced the explicit iterator-based <span style="color:#2e74b5;">for</span> loop with:
</p>
<p style="margin-left:36pt;">(a) a range-based <span style="color:#2e74b5;">for</span> loop?
</p>
<p style="margin-left:36pt;">(b) a standard library algorithm call?
</p>
<p>Demonstrate. (Note: As with GotW #2, don&#8217;t change the semantics of the function, even though they could be improved.)
</p>
<p>To recap, here is the mostly-fixed function:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( const list&lt;employee&gt;&amp; emps, const string&amp; name ) {<br />    for( auto i = begin(emps);  i != end(emps); ++i ) {<br />        if( i-&gt;name() == name ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    return "";<br />}
</code></pre></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1888&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/13/gotw-3-using-the-standard-library-or-temporaries-revisited-310/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #2 Solution: Temporary Objects</title>
		<link>http://herbsutter.com/2013/05/13/gotw-2-solution-temporary-objects/</link>
		<comments>http://herbsutter.com/2013/05/13/gotw-2-solution-temporary-objects/#comments</comments>
		<pubDate>Mon, 13 May 2013 12:30:54 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1874</guid>
		<description><![CDATA[Unnecessary and/or temporary objects are frequent culprits that can throw all your hard work—and your program&#8217;s performance—right out the window. How can you spot them and avoid them?   Problem JG Question 1. What is a temporary object? Guru Question 2. You are doing a code review. A programmer has written the following function, which [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1874&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Unnecessary and/or temporary objects are frequent culprits that can throw all your hard work—and your program&#8217;s performance—right out the window. How can you spot them and avoid them?<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is a temporary object?
</p>
<h2>Guru Question<br />
</h2>
<p>2. You are doing a code review. A programmer has written the following function, which uses unnecessary temporary or extra objects in at least three places. How many can you identify, and how should the programmer fix them?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( list&lt;employee&gt; emps, string name ) {<br />    for( auto i = begin(emps); i != end(emps); i++ ) {<br />        if( *i == name ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    return "";<br />}
</code></pre>
</p>
<p>Do not change the operational semantics of this function, even though they could be improved.
</p>
<p>
 </p>
<h1>Solution<br />
</h1>
<h2>1. What is a temporary object?<br />
</h2>
<p>Informally, a temporary object is an unnamed object that you can&#8217;t take the address of. A temporary is often created as an intermediate value during the evaluation of an expression, such as an object created by returning a value from a function, performing an implicit conversion, or throwing an exception. We usually call a temporary object an &#8220;rvalue,&#8221; so named because it can appear on the &#8220;r&#8221;ight hand side of an assignment. Here are some simple examples:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code><span style="background-color:yellow;">widget</span> f();            // f returns a temporary widget object<br /><br />auto a = 0, b = 1;<br />auto c = <span style="background-color:yellow;">a + b</span>;        // "a+b" creates a temporary int object
</code></pre>
</p>
<p>In contrast, in the same code we have objects like <span style="color:#2e74b5;">a</span> and <span style="color:#2e74b5;">c</span> that do each have a name and a memory address. Such an object is usually called an &#8220;lvalue,&#8221; because it can appear on the &#8220;l&#8221;eft hand side of an assignment.
</p>
<p>That&#8217;s a simplification of the truth, but it&#8217;s generally all you need to know. More precisely, C++ now has five categories of values, but distinguishing them is primarily useful for writing down the language specification, and you can mostly ignore them and just think about &#8220;rvalues&#8221; for temporary objects without names and whose addresses can&#8217;t be taken, and &#8220;lvalues&#8221; for non-temporary objects that have names and whose addresses can be taken.
</p>
<p>
 </p>
<h2>2. How many unnecessary temporary objects can you identify, and how should the programmer fix them?<br />
</h2>
<p>Believe it or not, this short function harbors three obvious cases of unnecessary temporaries or extra copies of objects, two subtler ones, and three red herrings.
</p>
<h3>The parameters are passed by value.<br />
</h3>
<p>The most obvious extra copies are buried in the function signature itself:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>  string find_addr( list&lt;employee&gt; emps, string name )
</code></pre>
</p>
<p>The parameters should be passed by <span style="color:#2e74b5;">const&amp;</span>—that is, <span style="color:#2e74b5;">const list&lt;employee&gt;&amp;</span> and <span style="color:#2e74b5;">const string&amp;</span>, respectively—instead of by value. Pass-by-value forces the compiler to make complete copy of both objects, which can be expensive and, here, is completely unnecessary.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer passing a read-only parameter by <strong>const&amp;</strong> if you are only going to read from it (not make a copy of it).
</p>
</blockquote>
<p>Pedantic note: Yes, with pass-by-value, if the caller passed a temporary <span style="color:#2e74b5;">list</span> or <span style="color:#2e74b5;">string</span> argument then it could be moved from rather than copied. But I&#8217;m deliberately saying &#8220;forces the compiler to make a complete copy&#8221; here because no caller is realistically going to be passing a temporary <span style="color:#2e74b5;">list</span> to <span style="color:#2e74b5;">find_addr</span>, except by mistake.
</p>
<h3>Non-issue: Initializing with &#8220;=&#8221;.<br />
</h3>
<p>Next we come to the first red herring, in the <span style="color:#2e74b5;">for</span> loop&#8217;s initialization:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    for( auto i = begin(emps); /*...*/ )
</code></pre>
</p>
<p>You might be tempted to say that this code should prefer to be spelled <span style="color:#2e74b5;">auto i(begin(emps))</span> rather than <span style="color:#2e74b5;">auto i = begin(emps)</span>, on the grounds that the <span style="color:#2e74b5;">=</span> syntax incurs an extra temporary object, even if it might be optimized away. After all, as we saw in GotW #1, usually that extra <span style="color:#2e74b5;">=</span> means the two-step &#8220;convert to a temporary then copy/move&#8221; of copy-initialization—but recall that doesn&#8217;t apply when using <span style="color:#2e74b5;">auto</span> like this. Why?
</p>
<p>Remember that <span style="color:#2e74b5;">auto</span> always deduces the exact type of the initializer expression, minus top-level <span style="color:#2e74b5;">const</span> and <span style="color:#2e74b5;">&amp;</span> which don&#8217;t matter for conversions, and so… presto! there cannot be any need for a conversion and we directly construct <span style="color:#2e74b5;">i</span>.
</p>
<p>So there is no difference between <span style="color:#2e74b5;">auto i(begin(emps))</span> and <span style="color:#2e74b5;">auto i = begin(emps)</span>. Which syntax you choose is up to you, but it depends only on taste, not on temporaries or any other performance or semantic difference.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer declaring variables using <strong>auto</strong>. Among other reasons to do so, it naturally guarantees zero extra temporaries due to implicit conversions.
</p>
</blockquote>
<h3>The end of the range is recalculated on each loop iteration.<br />
</h3>
<p>Another potential avoidable temporary occurs in the <span style="color:#2e74b5;">for</span> loop&#8217;s termination condition:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>  for( /*...*/ ; i != end(emps); /*...*/ )
</code></pre>
</p>
<p>For most containers, including <span style="color:#2e74b5;">list</span>, calling <span style="color:#2e74b5;">end()</span> returns a temporary object that must be constructed and destroyed, even though the value will not change.
</p>
<p>Normally when a value will not change, instead of recomputing it (and reconstructing and redestroying it) on every loop iteration, we would want to compute the value only once, store it in a local object, and reuse it.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer precomputing values that won&#8217;t change, instead of recreating objects unnecessarily.
</p>
</blockquote>
<p>However, a caution is in order: In practice, for simple inline functions like <span style="color:#2e74b5;">list&lt;T&gt;::end()</span> in particular used in a loop, compilers routinely notice their values won&#8217;t change and hoist them out of the loop for you without you having to do it yourself. So I actually don&#8217;t recommend any change to hoist the <span style="color:#2e74b5;">end</span> calculation here, because that would make the code slightly more complex and the definition of premature optimization is making the code more complex in the name of efficiency without data that it&#8217;s actually needed. Clarity comes first:
</p>
<blockquote><p><strong><em>Definition</em>: Premature optimization</strong> is when you make code more complex in the name of efficiency without data that it&#8217;s actually needed.
</p>
</blockquote>
<blockquote><p><strong>Guideline:</strong> Write for clarity and correctness first. Don&#8217;t optimize prematurely, before you have profiler data proving the optimization is needed, especially in the case of calls to simple inline calls to short functions that compilers normally can handle for you.
</p>
</blockquote>
<h3>The iterator increment uses postincrement.<br />
</h3>
<p>Next, consider the way we increment <span style="color:#2e74b5;">i</span> in the for loop:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>  for( /*...*/ ; i++ )
</code></pre>
</p>
<p>This temporary is more subtle, but it&#8217;s easy to understand once you remember how preincrement and postincrement differ. Postincrement is usually less efficient than preincrement because it has to remember and return its original value.
</p>
<p>Postincrement for a class <span style="color:#2e74b5;">T</span> should normally be implemented using the canonical form as follows:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>T T::operator++(int)() {<br />    auto old = *this; // remember our original value<br />    ++*this;          // always implement postincr in terms of preincr<br />    return old;       // return our original value<br />}
</code></pre>
</p>
<p>Now it&#8217;s easy to see why postincrement is less efficient than preincrement: Postincrement has to do all the same work as preincrement, but in addition it also has to construct and return another object containing the original value.
</p>
<blockquote><p><strong>Guideline:</strong> For consistency, always implement postincrement in terms of preincrement, otherwise your users will get surprising (and often unpleasant) results.
</p>
</blockquote>
<p>In the problem&#8217;s code, the original value is never used, and so there&#8217;s no reason to use postincrement. Preincrement should be used instead. Although the difference is unlikely to matter for a built-in type or a simple iterator type, where the compiler can often optimize away the extra unneeded work for you, it&#8217;s still a good habit not to ask for more than you need.
</p>
<blockquote><p><strong>Guideline:</strong> Prefer preincrement. Only use postincrement if you&#8217;re going to use the original value.
</p>
</blockquote>
<p> &#8220;But wait, you&#8217;re being inconsistent!&#8221; I can just hear someone saying. &#8220;That&#8217;s premature optimization. You said that compilers can hoist the <span style="color:#2e74b5;">end()</span> call out of the loop, and it&#8217;s just as easy for a compiler to optimize away this postincrement temporary.&#8221;
</p>
<p>That&#8217;s true, but it doesn&#8217;t imply premature optimization. Preferring <span style="color:#2e74b5;">++i</span> does not mean writing more complex code in the name of performance before you can prove it&#8217;s needed—<span style="color:#2e74b5;">++i</span> is not more complex than <span style="color:#2e74b5;">i++</span>, so it&#8217;s not as if you need performance data to justify using it! Rather, preferring <span style="color:#2e74b5;">++i</span> is <em>avoiding premature pessimization</em>, which means avoiding writing equivalently complex code that needlessly asks for extra work that it&#8217;s just going to ignore anyway.
</p>
<blockquote><p><strong><em>Definition</em>: Premature pessimization</strong> is when you write code that is slower than it needs to be, usually by asking for unnecessary extra work, when equivalently complex code would be faster and should just naturally flow out of your fingers.
</p>
</blockquote>
<h3>The comparison might use an implicit conversion.<br />
</h3>
<p>Next, we come to this:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    if( *i == name )
</code></pre>
</p>
<p>The <span style="color:#2e74b5;">employee</span> class isn&#8217;t shown in the problem, but we can deduce a few things about it. For this code to work, <span style="color:#2e74b5;">employee</span> likely must either have a conversion to <span style="color:#2e74b5;">string</span> or a conversion constructor taking a <span style="color:#2e74b5;">string</span>. Both cases create a temporary object, invoking either <span style="color:#2e74b5;">operator==</span> for <span style="color:#2e74b5;">string</span>s or <span style="color:#2e74b5;">operator==</span> for <span style="color:#2e74b5;">employee</span>s. (Only if there does happen to be an <span style="color:#2e74b5;">operator==</span> that takes one of each, or <span style="color:#2e74b5;">employee</span> has a conversion to a reference, that is, <span style="color:#2e74b5;">string&amp;</span>, is a temporary not needed.)
</p>
<blockquote><p><strong>Guideline: </strong>Watch out for hidden temporaries created by implicit conversions. One good way to avoid this is to make constructors and conversion operators <strong>explicit</strong> by default unless implicit conversions are really desirable.
</p>
</blockquote>
<h3>Probably a non-issue: return &#8220;&#8221;.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    return "";
</code></pre>
</p>
<p>Here we unavoidably create a temporary (unless we change the return type, but we shouldn&#8217;t; see below), but the question is: Is there a better way?
</p>
<p>As written, <span style="color:#2e74b5;">return &#8220;&#8221;;</span> calls the <span style="color:#2e74b5;">string</span> constructor that takes a <span style="color:#2e74b5;">const char*</span>, and if the <span style="color:#2e74b5;">string</span> implementation you&#8217;re using either (a) is smart enough to check for the case where it&#8217;s being passed an empty string, or (b) uses the small string optimization (SSO) that stores strings up to a certain size directly within the string object instead of on the heap, no heap allocation will happen.
</p>
<p>Indeed, every <span style="color:#2e74b5;">string</span> implementation I checked is smart enough not to perform an allocation here, which is maximally efficient for <span style="color:#2e74b5;">string</span>, and so in practice there&#8217;s nothing to optimize. But what alternatives do we have? Let&#8217;s consider two.
</p>
<p>First, you might consider re-spelling this as <span style="color:#2e74b5;">return &#8220;&#8221;s;</span> which is new in C++14. That essentially relies on the same implementation smarts to check for empty strings or to use SSO, just in a different function—the literal <span style="color:#2e74b5;">operator&#8221;"</span>.
</p>
<p>Second, you might consider re-spelling this as <span style="color:#2e74b5;">return { };</span>. On implementations that are both non-smart <em>and</em> non-SSO, this might have a slight advantage over the others because it invokes the default constructor, and so even the most naïve implementation is likely not to do an allocation since clearly no value is needed.
</p>
<p>In summary, there&#8217;s no difference in practice among returning <span style="color:#2e74b5;">&#8220;&#8221;</span>, <span style="color:#2e74b5;">&#8220;&#8221;s</span>, or <span style="color:#2e74b5;">{ }</span>; use whichever you prefer for stylistic reasons. If your <span style="color:#2e74b5;">string</span> implementation is either smart or uses SSO, which covers all implementations I know of, there&#8217;s exactly zero allocation difference.
</p>
<p>Note: SSO is a wonderful optimization for avoiding allocation overhead and contention, and every modern <span style="color:#2e74b5;">string</span> ought to use it. If your <span style="color:#2e74b5;">string</span> implementation doesn&#8217;t use SSO (as of this writing, I&#8217;m looking at you, libstdc++), write to your standard library implementer—it really should.
</p>
<h3>Non-issue: Multiple returns.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>    return i-&gt;addr;<br />    return "";
</code></pre>
</p>
<p>This was a second subtle red herring, designed to lure in errant disciples of the &#8220;single-entry/single-exit&#8221; (SE/SE) persuasion.
</p>
<p>I In the past, I&#8217;ve heard some people argue that it&#8217;s better to declare a local <span style="color:#2e74b5;">string</span> object to hold the return value and have a single <span style="color:#2e74b5;">return</span> statement that returns that <span style="color:#2e74b5;">string</span>, such as writing <span style="color:#2e74b5;">string ret; &#8230; ret = i-&gt;addr; break; &#8230; return ret;</span>. The idea, they say, is that this will assist the optimizer perform the &#8216;named return value optimization.&#8217;
</p>
<p>The truth is that whether single-return will improve or degrade performance can depend greatly on your actual code and compiler. In this case, the problem is that creating a single local <span style="color:#2e74b5;">string</span> object and then assigning it would mean calling string&#8217;s default constructor <em>and</em> then possibly its assignment  operator, instead of just a single constructor as in our original code. &#8220;But,&#8221; you ask, &#8220;how expensive could a plain old <span style="color:#2e74b5;">string</span> default constructor be?&#8221; Well, here&#8217;s how the &#8220;two-return&#8221; version performed on one popular compiler last time I tried it:
</p>
<ul>
<li>with optimizations disabled: two-return 5% faster than a &#8220;return value&#8221; <span style="color:#2e74b5;">string</span> object
</li>
<li>with aggressive optimizations: two-return 40% faster than a &#8220;return value&#8221; <span style="color:#2e74b5;">string</span> object
</li>
</ul>
<p>Note what this means: Not only did the single-return version generate slower code on this particular compiler on this particular day, but the slowdown was greater with optimizations turned on. In other words, a single-return version didn&#8217;t assist optimization, but actively interfered with it by making the code more complex.
</p>
<p>In general, note that SE/SE is an obsolete idea and has always been wrong. &#8220;Single entry,&#8221; or the idea that functions should always be entered in one place (at their start) and not with <span style="color:#2e74b5;">goto</span> jumps from the caller&#8217;s code directly to random places inside the function body, was and is an immensely valuable advance in computer science. It&#8217;s what made libraries possible, because it meant you could package up a function and reuse it and the function would always know its starting state, where it begins, regardless of the calling code. &#8220;Single exit,&#8221; on the other hand, got unfairly popular on the basis of optimization (&#8216;if there&#8217;s a single <span style="color:#2e74b5;">return</span> the compiler can perform return value optimization better&#8217;—see counterexample above) and symmetry (&#8216;if single entry is good, single exit must be good too&#8217;) but that is wrong because the reasons don&#8217;t hold in reverse—allowing a caller to jump in is bad because it&#8217;s not under the function&#8217;s control, but allowing the function itself to return early when it knows it&#8217;s done is perfectly fine and fully under the function&#8217;s control. To put the final nail in the coffin, note that &#8220;single exit&#8221; has always been a fiction in any language that has exceptions, because you can get an early exceptional return from any point where you call something that could throw an exception.
</p>
<h3>Non-issue: Return by value.<br />
</h3>
<p>Which brings us to the third red herring:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( /*...*/ )
</code></pre>
</p>
<p>Because C++ naturally enables move semantics for returned values like this <span style="color:#2e74b5;">string</span> object, there&#8217;s usually little to be gained by trying to avoid the temporary when you return by value. For example, if the caller writes <span style="color:#2e74b5;">auto address = find_addr( mylist, &#8220;Marvin the Robot&#8221; );</span>, there will be at most a cheap move (not a deep copy) of the returned temporary into <span style="color:#2e74b5;">address</span>, and compilers are allowed to optimize away even that cheap move and construct the result into <span style="color:#2e74b5;">address</span> directly.
</p>
<p>But what if you did feel tempted to try to avoid a temporary in all return cases by returning a <span style="color:#2e74b5;">string&amp;</span> instead of <span style="color:#2e74b5;">string</span>? Here&#8217;s one way you might try doing it that avoids the pitfall of returning a dangling reference to a local or temporary object:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>const string&amp; find_addr( /* ... */ ) {<br />    for( /* ... */ ) {<br />        if( /* found */ ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    static const string empty;<br />    return empty;<br />}
</code></pre>
</p>
<p>To demonstrate why this is brittle, here&#8217;s an extra question:
</p>
<p><strong>For the above function, write the documentation for how long the returned reference is valid.<br />
</strong></p>
<p>Go ahead, we&#8217;ll wait.
</p>
<p>Done? Okay, let&#8217;s consider: If the object is found, we are returning a reference to a <span style="color:#2e74b5;">string</span> inside an <span style="color:#2e74b5;">employee</span> object inside the <span style="color:#2e74b5;">list</span>, and so the reference itself is only valid for the lifetime of said <span style="color:#2e74b5;">employee</span> object inside the <span style="color:#2e74b5;">list</span>. So we might try something like this (assuming an empty address is not valid for any employee):
</p>
<blockquote><p>&#8220;If the returned string is nonempty, then the reference is valid until the next time you modify the employee object for which this is the address, including if you remove that employee from the list.&#8221;
</p>
</blockquote>
<p>Those are very brittle semantics, not least because the first (but far from only) problem that immediately arises is that the caller has no idea which employee that is—not only doesn&#8217;t he have a pointer or reference to the right <span style="color:#2e74b5;">employee</span> object, but he may not even be able to easily figure out which one it is if two employees could have the same address. Second, calling code can be notoriously forgetful and careless about the lifetimes of the returned reference, as in the following code which compiles just fine:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>auto&amp; a = find_addr( emps, "John Doe" );  // yay, avoided temporary!<br />emps.clear();<br />cout &lt;&lt; a;                                // oops
</code></pre>
</p>
<p>When the calling code does something like this and uses a reference beyond its lifetime, the bug will typically be intermittent and very difficult to diagnose. Indeed, one of the most common mistakes programmers make with the standard library is to use iterators after they are no longer valid, which is pretty much the same thing as using a reference beyond its lifetime; see GotW #18 for details about the accidental use of invalid iterators.
</p>
<h2>Summary<br />
</h2>
<p>There are some other optimization opportunities. Ignoring these for now, here is one possible corrected version of <span style="color:#2e74b5;">find_addr</span> which fixes the unnecessary temporaries. To avoid a possible conversion in the <span style="color:#2e74b5;">employee</span>/<span style="color:#2e74b5;">string</span> comparison, we&#8217;ll assume there&#8217;s something like an <span style="color:#2e74b5;">employee::name()</span> function and that <span style="color:#2e74b5;">.name() == name</span> has equivalent semantics.
</p>
<p>Note another reason to prefer declaring local variables with <span style="color:#2e74b5;">auto</span>: Because the <span style="color:#2e74b5;">list&lt;employee&gt;</span> parameter is now <span style="color:#2e74b5;">const</span>, calling <span style="color:#2e74b5;">begin</span> and <span style="color:#2e74b5;">end</span> return a different type—not <span style="color:#2e74b5;">iterator</span>s but <span style="color:#2e74b5;">const_iterator</span>s—but <span style="color:#2e74b5;">auto</span> naturally deduces the right thing so you don&#8217;t have to remember to make that change in your code.
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( const list&lt;employee&gt;&amp; emps, const string&amp; name ) {<br />    for( auto i = begin(emps);  i != end(emps); ++i ) {<br />        if( i-&gt;name() == name ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    return "";<br />}
</code></pre>
</p>
<h2>Acknowledgments<br />
</h2>
<p>Thanks in particular to the following for their feedback to improve this article: &#8220;litb1,&#8221; Daan Nusman, &#8220;Adrian,&#8221; Michael Marcin, Ville Voutilainen, Rick Yorgason, &#8220;kkoehne,&#8221; and Olaf van der Spek.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1874&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/13/gotw-2-solution-temporary-objects/feed/</wfw:commentRss>
		<slash:comments>57</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #2: Temporary Objects</title>
		<link>http://herbsutter.com/2013/05/09/gotw-2-temporary-objects-510/</link>
		<comments>http://herbsutter.com/2013/05/09/gotw-2-temporary-objects-510/#comments</comments>
		<pubDate>Thu, 09 May 2013 16:42:09 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1855</guid>
		<description><![CDATA[Unnecessary and/or temporary objects are frequent culprits that can throw all your hard work — and your program&#8217;s performance — right out the window. How can you spot them and avoid them?   Problem JG Question 1. What is a temporary object? Guru Question 2. You are doing a code review. A programmer has written [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1855&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>Unnecessary and/or temporary objects are frequent culprits that can throw all your hard work — and your program&#8217;s performance — right out the window. How can you spot them and avoid them?<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is a temporary object?
</p>
<h2>Guru Question<br />
</h2>
<p>2. You are doing a code review. A programmer has written the following function, which uses unnecessary temporary objects in at least three places. How many can you identify, and how should the programmer fix them?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>string find_addr( list&lt;employee&gt; emps, string name ) {<br />    for( auto i = begin(emps); i != end(emps); i++ ) {<br />        if( *i == name ) {<br />            return i-&gt;addr;<br />        }<br />    }<br />    return "";<br />}
</code></pre>
</p>
<p>Do not change the operational semantics of this function, even though they could be improved.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1855&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/09/gotw-2-temporary-objects-510/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #1 Solution: Variable Initialization – or Is It?</title>
		<link>http://herbsutter.com/2013/05/09/gotw-1-solution/</link>
		<comments>http://herbsutter.com/2013/05/09/gotw-1-solution/#comments</comments>
		<pubDate>Thu, 09 May 2013 16:30:01 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1831</guid>
		<description><![CDATA[This first problem highlights the importance of understanding what you write. Here we have a few simple lines of code—most of which mean something different from all the others, even though the syntax varies only slightly.   Problem JG Question 1. What is the difference, if any, among the following? widget w; // (a)widget w(); [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1831&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>This first problem highlights the importance of understanding what you write. Here we have a few simple lines of code—most of which mean something different from all the others, even though the syntax varies only slightly.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is the difference, if any, among the following?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w;                   // (a)<br /><br />widget w();                 // (b)<br />widget w{};                 // (c)<br /><br />widget w(x);                // (d)<br />widget w{x};                // (e)<br /><br />widget w = x;               // (f)<br />widget w = {x};             // (g)<br /><br />auto w = x;                 // (h)<br />auto w = widget{x};         // (i)
</code></pre>
</p>
<h2>Guru Questions<br />
</h2>
<p>2. What do each of the following lines do?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>vector&lt;int&gt; v1( 10, 20 );   // (a)<br /><br />vector&lt;int&gt; v2{ 10, 20 };   // (b)
</code></pre>
</p>
<p>3. Besides the cases above, what other benefits are there to using <span style="color:#1f4e79;">{ }</span> to initialize objects?
</p>
<p>4. When should you use <span style="color:#1f4e79;">( )</span> vs. <span style="color:#1f4e79;">{ }</span> syntax to initialize objects? Why?
</p>
<p>
 </p>
<h1>Solution<br />
</h1>
<p>This puzzle demonstrates several things:
</p>
<ul>
<li>The difference between default initialization, direct initialization, copy initialization, and list initialization.
</li>
<li>The difference between using <span style="color:#1f4e79;">( )</span> and using <span style="color:#1f4e79;">{ }</span> for initialization.
</li>
<li>A red herring that isn&#8217;t initialization at all, and which modern C++ entirely avoids.
</li>
</ul>
<p>But, most important of all: If you stick to two simple Guidelines, which we&#8217;ll cover in #4, you can ignore most of these cases and the rules are pretty simple and deliver efficient performance by default.
</p>
<p>
 </p>
<h2>1. What is the difference, if any, among the following?<br />
</h2>
<p>Let&#8217;s consider the cases one by one.
</p>
<h3>(a) is default initialization.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w;                   // (a)
</code></pre>
</p>
<p>This code declares a variable named <span style="color:#1f4e79;">w</span>, of type <span style="color:#1f4e79;">widget</span>. For most types, it is initialized using the default constructor <span style="color:#1f4e79;">widget::widget()</span>.
</p>
<p>Note that <span style="color:#1f4e79;">w</span> is not initialized and contains garbage values if <span style="color:#1f4e79;">widget</span> happens to be a built-in type like <span style="color:#1f4e79;">int</span>, or a simple &#8220;<span style="color:#1f4e79;">int</span>-like&#8221; class type with what&#8217;s called a &#8220;trivial&#8221; default constructor—a type that relies on the compiler-generated default constructor, has no virtual functions or virtual base classes or data member initializers, and all its bases and members satisfy the same restrictions.
</p>
<h3> (b) is a &#8220;vexing&#8221; red herring, now mostly a historical curiosity.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w();                 // (b)
</code></pre>
</p>
<p>This is a pre-modern C++ pitfall: At first glance, it may look like just another variable declaration calling a default constructor <span style="color:#1f4e79;">widget::widget()</span>; in reality, thanks to a grammar ambiguity, it&#8217;s a function declaration for a function named <span style="color:#1f4e79;">w</span> that takes no parameters and returns a <span style="color:#1f4e79;">widget</span> object by value. (If you can&#8217;t see this at first, consider that the above code is no different from writing something like <span style="color:#1f4e79;">int f();</span> which is clearly a function declaration.)
</p>
<p>Lest you think &#8220;aw, but those <span style="color:#1f4e79;">( )</span> parentheses are redundant, it&#8217;s the programmer&#8217;s own fault for not just writing <span style="color:#1f4e79;">widget w;</span> there!&#8221;, note that the same problem arises in those occasional cases where you think you&#8217;re initializing a variable with temporary objects:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>// same problem (gadget and doodad are types)<br />//<br />widget w( gadget(), doodad() );  // pitfall: not a variable declaration
</code></pre>
</p>
<p>Scott Meyers long ago named this &#8220;C++&#8217;s most vexing parse,&#8221; because the standard resolves the parsing ambiguity by saying: &#8220;if it can be a function declaration, it is.&#8221;
</p>
<p>The good news is that this is now mostly a historical curiosity, not something you should encounter in new code, because C++11 removed this pitfall. Note that C++11 does not change the meaning of the code—C++11 has great backward compatibility with C++98, including that this ambiguity still has the same meaning it always had. Rather, C++11 solves this by providing a syntax that supersedes case (b) in nearly all cases, so that we don&#8217;t need to ever fall into this pit anymore:
</p>
<h3>(c) is non-vexing and clear.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w{};                 // (c)
</code></pre>
</p>
<p>Here we have the first reason to prefer <span style="color:#1f4e79;">{ }</span> to <span style="color:#1f4e79;">( )</span>: For any class type <span style="color:#1f4e79;">widget</span>, line (c) does the &#8220;best parts&#8221; of (a) and (b)—it always initializes the variable, and is never ambiguous with a function declaration. No vex, no fuss, no muss.
</p>
<p>&#8220;Aha, but wait, it&#8217;s not that simple!&#8221; someone might object. &#8220;What if <span style="color:#1f4e79;">widget</span> has a constructor that takes a <span style="color:#1f4e79;">std::initializer_list</span>? Those are greedy (preferred), so if <span style="color:#1f4e79;">widget</span> has one of those wouldn&#8217;t this call that?&#8221;
</p>
<p>The answer is no, this really is just as simple as it looks, because the standard is explicit that an empty <span style="color:#1f4e79;">{ }</span> list means to call the default constructor if available. However, it&#8217;s good to be aware of <span style="color:#1f4e79;">initializer_list</span>s, so let&#8217;s talk about those next.
</p>
<h3>(d) and (e) are direct initialization.<br />
</h3>
<p>Now let&#8217;s consider cases where we actually initialize <span style="color:#1f4e79;">w</span> from some existing variable:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w(x);                // (d)<br />widget w{x};                // (e)
</code></pre>
</p>
<p>Assuming <span style="color:#1f4e79;">x</span> is not the name of a type, these are both direct initialization. That&#8217;s because the variable <span style="color:#1f4e79;">w</span> is initialized &#8220;directly&#8221; from the value of <span style="color:#1f4e79;">x</span> by calling <span style="color:#1f4e79;">widget::widget(x)</span>. If <span style="color:#1f4e79;">x</span> is also of type <span style="color:#1f4e79;">widget</span>, this invokes the copy constructor. Otherwise, it invokes a converting constructor.
</p>
<p>However, note that the syntax <span style="color:#1f4e79;">{x}</span> creates an <span style="color:#1f4e79;">initializer_list</span>. If <span style="color:#1f4e79;">widget</span> has a constructor that takes an <span style="color:#1f4e79;">initializer_list</span>, that constructor is preferred; otherwise, if <span style="color:#1f4e79;">widget</span> has a constructor that takes whatever type <span style="color:#1f4e79;">x</span> is (possibly with conversions), that constructor is used.
</p>
<p>There are two major differences that make (e) superior to (d): First, like (c), syntax (e) is unambiguous and avoids the vexing parse. If <span style="color:#1f4e79;">x</span> is a type name, then (d) is a function declaration even if there is also a variable named <span style="color:#1f4e79;">x</span> in scope (see above), whereas (e) is never a function declaration.
</p>
<p>Second, syntax (e) is safer because it does not allow narrowing (a.k.a. &#8220;lossy&#8221;) conversions that are otherwise allowed for some built-in types. Consider:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code><span style="color:#c00000;">int i1( 12.345 );           // ok: toss .345, we didn't like it anyway<br /><span style="color:#00b050;">int i2{ 12.345 };           // error: would be lossy implicit narrowing
</span></span></code></pre>
</p>
<h3>(f) and (g) are copy initialization and copy list initialization.<br />
</h3>
<p>This brings us to our final two non-<span style="color:#1f4e79;">auto</span> cases:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w = x;               // (f)
</code></pre>
</p>
<p>This is called &#8220;copy initialization.&#8221; Conceptually, the variable <span style="color:#1f4e79;">w</span> is initialized using <span style="color:#1f4e79;">widget</span>&#8216;s move or copy constructor, possibly after calling another function to convert the argument implicitly (<span style="color:#1f4e79;">explicit</span> conversions won&#8217;t be invoked here).
</p>
<blockquote><p><strong>Common Mistake:</strong> This is always initialization; it is never assignment, and so it never calls <strong>T::operator=()</strong>. Yes, I know there&#8217;s an &#8220;<strong>=</strong>&#8221; character in there, but don&#8217;t let that throw you — that&#8217;s just a syntax holdover from C, not an assignment operation.
</p>
</blockquote>
<p>Here are the semantics:
</p>
<ul>
<li>If <span style="color:#1f4e79;">x</span> is of type <span style="color:#1f4e79;">widget</span>, line (f) means the same as (d) <span style="color:#1f4e79;">widget w(x);</span> except that <span style="color:#1f4e79;">explicit</span> constructors cannot be used. It&#8217;s guaranteed that only a single constructor is called.
</li>
<li>If <span style="color:#1f4e79;">x</span> is of some other type, <em>conceptually</em> the compiler first implicitly converts <span style="color:#1f4e79;">x</span> to a temporary <span style="color:#1f4e79;">widget</span> object, then move-constructs <span style="color:#1f4e79;">w</span> from that temporary rvalue, using copy construction as &#8220;the slow way to move&#8221; as a backup if no better move constructor is available. Assuming that an implicit conversion is available, (f) means the same as <span style="color:#1f4e79;">widget w( widget(x) );</span>.
</li>
</ul>
<p>Note that I said &#8220;conceptually&#8221; a few times above. That&#8217;s because <em>practically</em> compilers are allowed to, and routinely do, optimize away the temporary and, if an implicit conversion is available, convert (f) to (d), thus optimizing away the extra move operation. However, even when the compiler does this, the <span style="color:#1f4e79;">widget</span> copy constructor must still be accessible, even if is not called—the copy constructor&#8217;s side effects may or may not happen, that&#8217;s all.
</p>
<p>Now note the related syntax that adds &#8220;<span style="color:#1f4e79;">=</span>&#8220;:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w = {x};             // (g)
</code></pre>
</p>
<p>This is called &#8220;copy list initialization.&#8221; It means the same as <span style="color:#1f4e79;">widget w{x};</span> except that <span style="color:#1f4e79;">explicit</span> constructors cannot be used. It&#8217;s guaranteed that only a single constructor is called.
</p>
<h3>(h) and (i) are also copy initialization, but simpler.<br />
</h3>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>auto w = x;                 // (h)<br />auto w = widget{x};         // (i)
</code></pre>
</p>
<p>The semantics are just like (f) and (g), except simpler to teach, learn, and use because using <span style="color:#1f4e79;">auto</span> guarantees the right-hand expression&#8217;s type will be deduced exactly. Note that the (i) syntax works fine for both implicit and <span style="color:#1f4e79;">explicit</span> conversions.
</p>
<p>Line (h) means the same as (d), <span style="color:#1f4e79;"><em>type_of_x</em> w(x);</span>. Only a single copy constructor is called. This is <em>guaranteed to stay true</em> as the program evolves: Because line (h) does not commit to an explicit type, it is guaranteed to be both maximally efficient because there can be no conversion involved, and maximally robust under maintenance as the type of <span style="color:#1f4e79;">w</span> &#8220;auto&#8221;-matically tracks the type of <span style="color:#1f4e79;">x</span> which may change as the program is maintained.
</p>
<p>Line (i) is the most consistent spelling when you do want to commit to a specific type and explicitly request a conversion if needed, and once again the <span style="color:#1f4e79;">{ }</span> syntax happily avoids lossy narrowing conversions. In practice on most compilers, only a single constructor is called—similarly to what we saw with (f) and (g), conceptually there are two constructor calls, a converting or copy constructor to create a temporary <span style="color:#1f4e79;">widget{x}</span> followed by a move to move it to <span style="color:#1f4e79;">w</span>, but compilers routinely elide the latter.
</p>
<p>In general, I recommend that you try out these two forms, and increasingly prefer using them as you grow comfortable with them. I&#8217;m at the point where I&#8217;m now inclined to write virtually all of my local variable declarations this way. (I know some of you will be skeptical about this broad claim—more on &#8220;the <span style="color:#1f4e79;">auto</span> question&#8221; in another GotW.)
</p>
<p>
 </p>
<h2>2. What do each of the following lines do?<br />
</h2>
<p>In the Question 2 code, we&#8217;re creating a <span style="color:#1f4e79;">vector&lt;int&gt;</span> and passing the arguments <span style="color:#1f4e79;">10</span> and <span style="color:#1f4e79;">20</span> to its constructor—in the first case as <span style="color:#1f4e79;">( 10, 20 )</span> and in the second case as <span style="color:#1f4e79;">{ 10, 20 }</span>.
</p>
<p>Both will call a constructor, but which one(s)? Well, <span style="color:#1f4e79;">vector&lt;int&gt;</span> has several constructors that can take two parameters, but only two could be correctly called with the parameters <span style="color:#1f4e79;">10</span> and <span style="color:#1f4e79;">20</span>. Ignoring defaulted optional allocator parameters for simplicity, the two constructors are:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>vector( size_t n, const int&amp; value );    // A: n copies of value<br /><br />vector( initializer_list&lt;int&gt; values );  // B: copy of values
</code></pre>
</p>
<p>There are two simple C++ rules that tell us which one will be called for the code in question:
</p>
<ul>
<li>The syntax <span style="color:#1f4e79;">{ /*…*/ }</span> used in an expression context gives you an <span style="color:#1f4e79;">initializer_list</span>.
</li>
<li>Constructors that take an <span style="color:#1f4e79;">initializer_list</span> are preferred over other constructors, and so can hide other constructors that might otherwise be viable.
</li>
</ul>
<p>Armed with those two tidbits, the answer is simple:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>vector&lt;int&gt; v1( 10, 20 );    // (a) calls A: 10 copies of the value 20<br />assert( v1.size() == 10 );<br /><br />vector&lt;int&gt; v2{ 10, 20 };    // (b) calls B: the values 10 and 20<br />assert( v2.size() == 2 );
</code></pre>
</p>
<p>
 </p>
<h2>3. Besides the cases above, what other benefits are there to using { } to initialize objects?<br />
</h2>
<p>For one thing, it&#8217;s called &#8220;uniform initialization&#8221; because it&#8217;s, well, uniform—the same for all types, including aggregate structs and arrays and <span style="color:#1f4e79;">std::</span> containers, and without the &#8220;vexing parse&#8221; annoyance:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>struct mystruct { int x, y; };<br /><br />// C++98 <br />rectangle       w( origin(), extents() );       // oops, vexing parse <br />complex&lt;double&gt; c( 2.71828, 3.14159 ); <br />mystruct        m = { 1, 2 };<br />int             a[] = { 1, 2, 3, 4 };<br />vector&lt;int&gt;     v;                              // urk, need more code<br />for( int i = 1; i &lt;= 4; ++i ) v.push_back(i);   //   to initialize this<br /><br />// C++11 (note: "=" is mostly optional)<br />rectangle       w   = { origin(), extents() }; <br />complex&lt;double&gt; c   = { 2.71828, 3.14159 }; <br />mystruct        m   = { 1, 2 }; <br />int             a[] = { 1, 2, 3, 4 };<br />vector&lt;int&gt;     v   = { 1, 2, 3, 4 };
</code></pre>
</p>
<p>And note that this isn&#8217;t just an aesthetic issue. Consider writing generic code that should be able to initialize any type… and while we&#8217;re at it, let&#8217;s gratuitously use perfect forwarding as an example:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>template&lt;typename T, typename ...Args&gt;<br />void forwarder( Args&amp;&amp;... args ) {<br />    // ...<br />    T local <span style="background-color:yellow;">= {</span> std::forward&lt;Args&gt;(args)... <span style="background-color:yellow;">}</span>;<br />    // ...<br />}<br /><br />forwarder&lt;int&gt;            ( 42 );                  // ok<br />forwarder&lt;rectangle&gt;      ( origin(), extents() ); // ok<br />forwarder&lt;complex&lt;double&gt;&gt;( 2.71828, 3.14159 );    // ok<br />forwarder&lt;mystruct&gt;       ( 1, 2 );                // ok because of {}<br />forwarder&lt;int[]&gt;          ( 1, 2, 3, 4 );          // ok because of {}<br />forwarder&lt;vector&lt;int&gt;&gt;    ( 1, 2, 3, 4 );          // ok because of {}
</code></pre>
</p>
<p>The last three lines would not be legal if <span style="color:#1f4e79;">forwarder</span> used <span style="color:#1f4e79;">( )</span> initialization syntax internally.
</p>
<p>The new <span style="color:#1f4e79;">{ }</span> syntax works pretty much everywhere, including to initialize members:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget::widget( /*...*/ ) : mem1<span style="background-color:yellow;">{</span>init1<span style="background-color:yellow;">}</span>, mem2<span style="background-color:yellow;">{</span>init2, init3<span style="background-color:yellow;">}</span> { /*...*/ } 
</code></pre>
</p>
<p>And, as icing on the take, it&#8217;s often just plain convenient to pass function arguments, or return a value, without a type-named temporary:
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>void draw_rect( rectangle ); <br /><br />draw_rect( rectangle(origin, selection) );         // C++98<br />draw_rect(<span style="background-color:yellow;">{</span> origin, selection <span style="background-color:yellow;">}</span>);                  // C++11<br /><br />rectangle compute_rect() {<br />   // ...<br />   if(cpp98) return rectangle(origin, selection);  // C++98<br />   else      return <span style="background-color:yellow;">{</span>origin, selection<span style="background-color:yellow;">}</span>;           // C++11<br />}
</code></pre>
</p>
<p>
 </p>
<h2>4. When should you use ( ) vs. { } syntax to initialize objects? Why?<br />
</h2>
<p>Here&#8217;s the simple <span style="color:#5b9bd5;">g</span>uideline:
</p>
<blockquote><p><strong>Guideline:</strong> Prefer to use initialization with <strong>{ }</strong>, such as <strong>vector&lt;int&gt; v = { 1, 2, 3, 4 };</strong> or <strong>auto v = vector&lt;int&gt;{ 1, 2, 3, 4 };</strong>, because it&#8217;s more consistent, more correct, and avoids having to know about old-style pitfalls at all. In single-argument cases where you prefer to see only the <strong>=</strong> sign, such as <strong>int i = 42;</strong> and <strong>auto x = anything</strong>; omitting the braces is fine. …
</p>
</blockquote>
<p>That covers the vast majority of cases. There is only one main exception:
</p>
<blockquote><p>… In rare cases, such as <strong>vector&lt;int&gt; v(10,20);</strong> or <strong>auto v = vector&lt;int&gt;(10,20);</strong>, use initialization with <strong>( )</strong> to explicitly call a constructor that is otherwise hidden by an <strong>initializer_list</strong> constructor.
</p>
</blockquote>
<p>However, the reason this should be generally &#8220;rare&#8221; is because default and copy construction are already special and work fine with <span style="color:#5b9bd5;">{ }</span>, and good class design now mostly avoids the resort-to-<span style="color:#5b9bd5;">( )</span> case for user-defined constructors because of this final design guideline:
</p>
<blockquote><p><strong>Guideline: </strong>When you design a class, avoid providing a constructor that ambiguously overloads with an <strong>initializer_list</strong> constructor, so that users won&#8217;t need to use <strong>( )</strong> to reach such a hidden constructor.
</p>
</blockquote>
<p>
 </p>
<h2>Acknowledgments<br />
</h2>
<p>Thanks in particular to the following for their feedback to improve this article: Michal Mocny, Jay Miller, &#8220;Alexey,&#8221; &#8220;praetorian20,&#8221; Francisco Lopes, &#8220;Neil,&#8221; Daryle Walker.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1831&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/09/gotw-1-solution/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #1: Variable Initialization—or Is It? (3/10)</title>
		<link>http://herbsutter.com/2013/05/06/gotw-1-variable-initialization-or-is-it-310/</link>
		<comments>http://herbsutter.com/2013/05/06/gotw-1-variable-initialization-or-is-it-310/#comments</comments>
		<pubDate>Mon, 06 May 2013 08:26:40 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1828</guid>
		<description><![CDATA[This first problem highlights the importance of understanding what you write. Here we have a few simple lines of code — most of which mean something different from all the others, even though the syntax varies only slightly.   Problem JG Question 1. What is the difference, if any, among the following? widget w; // [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1828&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#5a5a5a;"><em>This first problem highlights the importance of understanding what you write. Here we have a few simple lines of code — most of which mean something different from all the others, even though the syntax varies only slightly.<br />
</em></span></p>
<p>
 </p>
<h1>Problem<br />
</h1>
<h2>JG Question<br />
</h2>
<p>1. What is the difference, if any, among the following?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>widget w;                   // (a)<br /><br />widget w();                 // (b)<br />widget w{};                 // (c)<br /><br />widget w(x);                // (d)<br />widget w{x};                // (e)<br /><br />widget w = x;               // (f)<br />widget w = {x};             // (g)<br /><br />auto w = x;                 // (h)<br />auto w = widget{x};         // (i)
</code></pre>
</p>
<h2>Guru Questions<br />
</h2>
<p>2. What do each of the following lines do?
</p>
<p style="background:#ffffcc;margin-left:14pt;">
<pre><code>vector&lt;int&gt; v1( 10, 20 );   // (a)<br /><br />vector&lt;int&gt; v2{ 10, 20 };   // (b)
</code></pre>
</p>
<p>3. Besides the cases above, what other benefits are there to using <span style="color:#2e74b5;">{ }</span> to initialize objects?
</p>
<p>4. When should you use <span style="color:#2e74b5;">( )</span> vs. <span style="color:#2e74b5;">{ }</span> syntax to initialize objects? Why?</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1828&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/06/gotw-1-variable-initialization-or-is-it-310/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Guru of the Week and the Exceptional C++ Series</title>
		<link>http://herbsutter.com/2013/05/04/guru-of-the-week-and-the-exceptional-c-series/</link>
		<comments>http://herbsutter.com/2013/05/04/guru-of-the-week-and-the-exceptional-c-series/#comments</comments>
		<pubDate>Sat, 04 May 2013 19:58:26 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1817</guid>
		<description><![CDATA[It’s time for me to pick up Guru of the Week (GotW) again in earnest, as part of work on revising my three Exceptional C++ books for today’s C++. Most Exceptional C++ Items are enhanced versions of GotW issues, after all, so the simplest and best place to start is with GotW. It’s also much [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1817&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>It’s time for me to pick up <em>Guru of the Week</em> (GotW) again in earnest, as part of work on revising my three <em>Exceptional C++</em> books for today’s C++. Most <em>Exceptional C++</em> Items are enhanced versions of GotW issues, after all, so the simplest and best place to start is with GotW. It’s also much easier to write (and read) one short piece at a time.</p>
<p>Last spring I wrote a few GotWs, but life got busy with the <a href="http://isocpp.org/about">Standard C++ Foundation</a>, <a href="http://isocpp.org">isocpp.org</a>, and <a href="http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting">C++14</a>. I was also trying to figure out what reasonable tools to use to write new Items, since I wanted to publish the same Item on this blog and then in e-book and dead tree editions, all with a single source while maintaining a pleasing format. I’ve found a provisional promising tool (Word!) and format for that I’ll try out for now, and you’ll see it in the next GotW issue to be posted soon.</p>
<p>But a major issue was figuring out the right balance between updating existing GotW issues and writing new ones.</p>
<p>Here’s where I landed…</p>
<p>&#160;</p>
<p><strong>First, I’ve decided to keep and revise nearly all of my existing Items.</strong> This is not an obvious choice: As a counterexample, some authors have decided to not revise their existing books, but to write new books about C++11, for various reasons including that they expect the advice in the earlier books is still current. I think the latter is partly true, because of course the topics are still current and the code still compiles – C++11 has a great backward compatibility story with C++98.</p>
<p>However, when I looked through my own articles and Items, every single one I looked at had two qualities: </p>
<ul>
<li>The topic was still current and useful, so it should still be covered. (With very rare exceptions like material discussing the now-removed <em>export</em> template feature.)</li>
<li>The code and discussion were addressed with C++98-era advice that is now dated and/or incomplete.</li>
</ul>
<p>For example, nearly every GotW’s code should just naturally use <em>auto </em>and <em>{ }</em> initialization. Most should use or actively discuss move semantics, lambdas, and other C++11 features. And it’s hard to write about existing features like virtual function overriding (as in GotW #5) without feeling something important is missing unless there’s also discussion of the way C++ has extended the existing feature, such as with <em>override</em> and <em>final</em>.</p>
<p>&#160;</p>
<p><strong>Second, I’ve decided not to target C++11 – rather, I’m going to write for C++14.</strong> Why would I do that, when C++ compilers <em>[preemptive snarky remark: including my own team’s]</em> are still catching up to C++11? For several good reasons:</p>
<ul>
<li>C++14 is going to be current C++ soon. As of April, it’s now feature-complete, and the detailed technical specification should be frozen this fall or winter (leaving time for ISO ballots and “’14” publication). Compilers and libraries are already aggressively implementing it. I wouldn’t be surprised if we had multiple fully-conforming C++14 implementations by the end of next year.</li>
<li>C++14 is a small delta, a minor release aimed mainly at “completing C++11.” And it <em>does </em>complete C++11 well, to the point where as an author I really want to teach the complete story. I want to teach the complete “avoid writing <em>new</em> and <em>delete</em>” guidance that C++14 <em>make_unique</em> fully enables so that I can stop mumbling “except when you create a <em>unique_ptr</em>” as a special case. I want to write generic lambdas with C++14’s terse <em>auto</em> parameters that makes lambdas shorter to write and more flexible, and stop repeating parameter type names. I want to use C++14 move-capture in lambdas that makes them complete, and not feel obliged to talk about artificially putting objects on the heap and capturing <em>shared_ptr</em>s to them by value as a workaround for lack of move capture. And, in a few places where appropriate, I want to be free to use a few smaller C++14 tidbits like <em>optional&lt;T&gt;</em> that can affect interface design guidance now that they’re in the draft standard.</li>
</ul>
<p>In addition, I’ve found that C++11/14 is changing my coding style, including my basic variable declaration style. I now think <em>auto </em>should be used consistently to declare local variables, even when you want to commit to a specific type(!) – this certainly surprised me, and likely will surprise you too, so I’ll cover that this year in a GotW and a recorded talk, no later than at <a href="http://cppandbeyond.com"><em>C++ and Beyond</em></a> later this year and possibly sooner.</p>
<p>&#160;</p>
<p>I’ve converged on the above by updating the first dozen <em>Exceptional C++</em> Items (in GotW order), trying out alternatives and seeing how well each one worked out. Those first dozen Items are now done and I’m pleased with the result, showing off <em>auto</em> and move and generic lambdas and mutexes/atomics and the new meanings of <em>const</em> and <em>mutable</em> and everything else, most of their code tested against various of the latest compilers, their advice updated to be current with current C++. And in every single GotW, no matter how short, it just felt <em>right</em> to:</p>
<ul>
<li>keep the topic, because each topic is still as relevant and useful as ever;</li>
<li>revise the C++98 code and advice, because in every case both the code examples and the discussion was dated and/or incomplete, usually both; and</li>
<li>skip C++11 to write directly for the complete story in C++14 without apology, because it let me avoid digressions for workarounds not needed in C++14, which made the text cleaner and simpler.</li>
</ul>
<p>As I’ve revised Items, I’ve found that some updates are small but pervasive, such as using <em>auto</em>. Others are extensive, with entire subsections completely rewritten, thrown out as no longer relevant, or newly added to cover essential new sides of the story in modern C++. For example, GotW #6 about <em>const</em>-correctness is now a two-parter, covering the new meanings of <em>const</em> and <em>mutable</em>. Watch for it soon.</p>
<p>&#160;</p>
<p>A word about numbering and sequence: My plan is to update and post most GotWs in numerical order starting with GotW #1, but every so often we’ll jump forward to new high numbers (starting with #89) as I create ones that weren’t originally a GotW – a Sutter’s Mill magazine article that wasn’t originally published as a GotW, or a brand-new C++14 topic. So for example you might see a sequence like “… 23, 24, <strong>91</strong>, 25, 26, …”. All GotWs will have substantial new material, but the newly minted high numbers will be entirely on brand-new topics that didn’t arise in C++98 or just weren’t covered in GotW form before. (The handful of GotWs I wrote last year will be renumbered as they’re folded into the original series, either as updates or with new numbers in the original sequence if they’re on completely new topics. )</p>
<p>&#160;</p>
<p>I’ll start posting fresh C++11/14 GotWs in the next few days. As usual, I’ll first post a problem by itself to invite discussion about possible solutions, then after there’s been time for comments I’ll post my own solution and the next problem.</p>
<p>It’s kind of exciting to write “GotW14” – today’s C++ really does feel like a fresh new language.</p>
<p>I hope you enjoy them as much as I enjoy writing them. </p>
<br />Filed under: <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1817&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/05/04/guru-of-the-week-and-the-exceptional-c-series/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Trip Report: ISO C++ Spring 2013 Meeting</title>
		<link>http://herbsutter.com/2013/04/20/trip-report-iso-c-spring-2013-meeting/</link>
		<comments>http://herbsutter.com/2013/04/20/trip-report-iso-c-spring-2013-meeting/#comments</comments>
		<pubDate>Sat, 20 Apr 2013 19:40:30 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1804</guid>
		<description><![CDATA[The Bristol meeting concluded a few hours ago, and I just posted my trip report on isocpp.org: This afternoon in Bristol, UK, the ISO C++ standards committee adopted generic lambdas, dynamic arrays (an improved version of C99 VLAs), variable templates, reader/writer locks, make_unique, optional&#60;T&#62;, standard library user-defined literals, and a number of other language and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1804&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://herbsutter.files.wordpress.com/2013/05/wg21-attendance.png"><img title="wg21-attendance" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="wg21-attendance" align="right" src="http://herbsutter.files.wordpress.com/2013/05/wg21-attendance_thumb.png?w=244&#038;h=168" width="244" height="168" /></a>The Bristol meeting concluded a few hours ago, and I just posted my <a href="http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting">trip report on isocpp.org</a>:</p>
<blockquote><p>This afternoon in Bristol, UK, the ISO C++ standards committee adopted generic lambdas, dynamic arrays (an improved version of C99 VLAs), variable templates, reader/writer locks, <code>make_unique</code>, <code>optional&lt;T&gt;</code>, standard library user-defined literals, and a number of other language and library improvements – and approved the result as the feature-complete Committee Draft (CD) of Standard C++14 to be distributed for its primary international review ballot.</p>
<p>In addition to completing the C++14 CD document, the committee also made progress on three additional important parallel specifications that are on track to be published around the same time as C++14:</p>
<ul>
<li><strong>File system</strong> library (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3505.html">draft</a>), based on Boost.FileSystem version 3. </li>
<li><strong>Networking</strong> library, small at first and regularly extended. </li>
<li><strong>“Concepts Lite”</strong> language extensions (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf">draft</a>), to express template constraints and improve template usability and error messages. </li>
</ul>
<p>Together these mark the C++ committee’s main planned deliverables for 2014. …</p>
<h4><strong>To provide just a sampling [of C++14], here are a few quick examples of some of the newly added features…</strong></h4>
</blockquote>
<p><a href="http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting">Continue reading&#8230;</a></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1804&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/04/20/trip-report-iso-c-spring-2013-meeting/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2013/05/wg21-attendance_thumb.png" medium="image">
			<media:title type="html">wg21-attendance</media:title>
		</media:content>
	</item>
		<item>
		<title>Complex initialization for a const variable</title>
		<link>http://herbsutter.com/2013/04/05/complex-initialization-for-a-const-variable/</link>
		<comments>http://herbsutter.com/2013/04/05/complex-initialization-for-a-const-variable/#comments</comments>
		<pubDate>Fri, 05 Apr 2013 18:12:28 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1792</guid>
		<description><![CDATA[On std-discussion, Shakti Misra asked: I have seen in a lot of places code like int i; if(someConditionIstrue) { Do some operations and calculate the value of i; i = some calculated value; } use i; //Note this value is only used not changed. It should not be changed. But unfortunately in this case there [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1792&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>On std-discussion, <a href="https://groups.google.com/a/isocpp.org/d/msg/std-discussion/FBjcR4WJlkU/wL1a28jWeeoJ">Shakti Misra asked</a>:</p>
<blockquote><p>I have seen in a lot of places code like     <br />int i;      <br />if(someConditionIstrue)      <br />{      <br />Do some operations and calculate the value of i;      <br />i = some calculated value;      <br />}      <br />use i; //Note this value is only used not changed. It should not be changed.      <br />But unfortunately in this case there is no way to guarantee it.      <br />so now if some one comes and does</p>
<p>i = 10;// This is valid</p>
<p>What i was thinking: is there a way to tell that &quot;i&quot; can be set only once?     <br />After that it will be a constant. Something like </p>
<p>const once int i;     <br />if(someConditionIstrue)      <br />{      <br />Do some operations and calculate the value of i;      <br />i = calculated value;      <br />}      <br />use i; //Note this value is only used not changed.      <br />i = 10;// Compiler error</p>
</blockquote>
<p>Olaf van der Spek replied:</p>
<blockquote><p>A lambda?</p>
</blockquote>
<p><a href="https://groups.google.com/a/isocpp.org/d/msg/std-discussion/FBjcR4WJlkU/nQnsSOziq04J">I answered</a> as follows:</p>
<p>Bingo. Olaf nailed it: The way to do it is with a lambda. This is one of the examples I give in my talk <em>Lambdas, Lambdas Everywhere</em> (here are the <u><a href="http://sdrv.ms/XtXofx">slides</a></u> from <em>C++ &amp; Beyond</em> 2010).</p>
<p>In your example, do this:</p>
<p>&#160;</p>
<p><strong>const</strong> int i = [&amp;]{</p>
<p>&#160;&#160;&#160; int i = some_default_value;</p>
<p>&#160;&#160;&#160; if(someConditionIstrue)   <br />&#160;&#160;&#160; {    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Do some operations and calculate the value of i;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; i = some calculated value;    <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; return i;</p>
<p>} <strong>()</strong>; // note: () invokes the lambda!</p>
<p>&#160;</p>
<p>That&#8217;s the C++11 idiom for this. It&#8217;s still being absorbed though – not everyone knows about it yet as we&#8217;re still all learning C++11 styles together.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1792&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/04/05/complex-initialization-for-a-const-variable/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Words of wisdom: Bjarne Stroustrup</title>
		<link>http://herbsutter.com/2013/03/14/words-of-wisdom-bjarne-stroustrup/</link>
		<comments>http://herbsutter.com/2013/03/14/words-of-wisdom-bjarne-stroustrup/#comments</comments>
		<pubDate>Thu, 14 Mar 2013 15:50:07 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Opinion & Editorial]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1790</guid>
		<description><![CDATA[Bjarne Stroustrup wrote the following a few minutes ago on the concepts mailing list: Let me take this opportunity to remind people that &#34;being able to do something is not sufficient reason for doing it&#34; and &#34;being able to do every trick is not a feature but a bug&#34; For the latter, remember Dijkstra&#8217;s famous [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1790&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Bjarne Stroustrup wrote the following a few minutes ago on the <a href="https://groups.google.com/a/isocpp.org/forum/?fromgroups#!searchin/concepts/goto$20dijkstra/concepts/IAHQkYcbCDc/nm8W86ozXQYJ">concepts mailing list</a>:</p>
<blockquote><p>Let me take this opportunity to remind people that</p>
<ul>
<li>&quot;being able to do something is not sufficient reason for doing it&quot; and</li>
<li>&quot;being able to do every trick is not a feature but a bug&quot;</li>
</ul>
<p>For the latter, remember Dijkstra&#8217;s famous &quot;Goto considered harmful&quot; paper. The point was not that the &quot;new features&quot; (loop constructs) could do every goto trick better/simpler, but that some of those tricks should be avoided to simplify good programming.</p>
<p>Concepts and concepts lite are meant to make good generic programming simpler. They are not meant to be a drop-in substitute for every metaprogramming and macroprogramming trick. If you are an expert, and if in your expert opinion you and your users really need those tricks, you can still use them, but we need to make many (most) uses of templates easier to get right, so that they can become more mainstream. That where concepts and concept lite fits in.</p>
<p>Some of you may find this hard to believe, but &quot;back then&quot; there was quite serious opposition to function declarations because &quot;they restricted the way functions could be used and the way separate compilation could be used&quot; and also serious opposition to virtual functions &quot;because pointers to functions are so much more flexible.&quot; I see concepts lite (and concepts) in the same light as goto/for, unchecked-function-arguments/function-declarations, pointers-to-functions/abstract-classes.</p>
</blockquote>
<p><font color="#666666">Reminds me of the related antipattern: “Something must be done. This is something. Therefore we must do it!”</font></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/opinion-editorial/'>Opinion &amp; Editorial</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1790&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/03/14/words-of-wisdom-bjarne-stroustrup/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>atomic Weapons: The C++ Memory Model and Modern Hardware</title>
		<link>http://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/</link>
		<comments>http://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/#comments</comments>
		<pubDate>Mon, 11 Feb 2013 18:31:42 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1784</guid>
		<description><![CDATA[Most of the talks I gave at C++ and Beyond 2012 last summer are already online at Channel 9. Here are two more. This is a two-part talk that covers the C++ memory model, how locks and atomics and fences interact and map to hardware, and more. Even though we&#8217;re talking about C++, much of [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1784&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><img align="right" src="http://herbsutter.files.wordpress.com/2013/02/021113_1851_atomicweapo1.png?w=500" alt="" />Most of the talks I gave at <a href="http://cppandbeyond.com"><em>C++ and Beyond 2012</em></a> last summer are already online at Channel 9. Here are two more.
</p>
<p>This is a two-part talk that covers the C++ memory model, how locks and atomics and fences interact and map to hardware, and more. Even though we&#8217;re talking about C++, much of this is also applicable to Java and .NET which have similar memory models, but not all the features of C++ (such as relaxed atomics).
</p>
<p>Note: This is about the basic structure and tools, not how to write lock-free algorithms using atomics. That next-level topic may be on deck for this year&#8217;s <a href="http://cppandbeyond.com/2013/02/11/cb-2013-dates-finalized-december-9-12-2013/"><em>C++ and Beyond</em> in December</a>, we&#8217;ll see…
</p>
<h2>atomic&lt;&gt; Weapons: The C++ Memory Model and Modern Hardware<br />
</h2>
<ul style="margin-left:72pt;">
<li><a href="http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2"><span style="background-color:yellow;"><strong>Part 1:</strong></span> Optimizations, races, and the memory model; acquire and release ordering; mutexes vs. atomics vs. fences</a>
		</li>
<li><a href="http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2"><span style="background-color:yellow;"><strong>Part 2:</strong></span> Restrictions on compilers and hardware (incl. common bugs); code generation and performance on x86/x64, IA64, POWER, ARM, and more; relaxed atomics; volatile</a>
		</li>
</ul>
<p>This session in one word: <em><strong>Deep.</strong><br />
		</em></p>
<p style="margin-left:36pt;">It&#8217;s a session that includes topics I&#8217;ve publicly said for years is Stuff You Shouldn&#8217;t Need To Know and I Just Won&#8217;t Teach, but it&#8217;s becoming achingly clear that people do need to know about it. Achingly, heartbreakingly clear, because some hardware incents you to pull out the big guns to achieve top performance, and C++ programmers just are so addicted to full performance that they&#8217;ll reach for the big red levers with the flashing warning lights. Since we can&#8217;t keep people from pulling the big red levers, we&#8217;d better document the A to Z of what the levers actually do, so that people don&#8217;t <a href="http://en.wikipedia.org/wiki/Scram"><em>SCRAM</em></a> unless they really, really, really meant to.<em><br />
		</em></p>
<p style="margin-left:36pt;"><strong>Topics Covered:</strong>
	</p>
<ul style="margin-left:72pt;">
<li><strong>The facts: </strong>The C++11 memory model and what it requires you to do to make sure your code is correct and stays correct. We&#8217;ll include clear answers to several FAQs: &#8220;how do the compiler and hardware cooperate to remember how to respect these rules?&#8221;, &#8220;what is a race condition?&#8221;, and the ageless one-hand-clapping question &#8220;how is a race condition like a debugger?&#8221;
</li>
<li><strong>The tools:</strong> The deep interrelationships and fundamental tradeoffs among mutexes, atomics, and fences/barriers. I&#8217;ll try to convince you why standalone memory barriers are bad, and why barriers should always be associated with a specific load or store.
</li>
<li><strong>The unspeakables: </strong>I&#8217;ll grudgingly and reluctantly talk about the Thing I Said I&#8217;d Never Teach That Programmers Should Never Need To Now: relaxed atomics. Don&#8217;t use them! If you can avoid it. But here&#8217;s what you need to know, even though it would be nice if you didn&#8217;t need to know it.
</li>
<li><strong>The rapidly-changing hardware reality: </strong>How locks and atomics map to hardware instructions on ARM and x86/x64, and throw in POWER and Itanium for good measure – and I&#8217;ll cover how and why the answers are actually different last year and this year, and how they will likely be different again a few years from now. We&#8217;ll cover how the latest CPU and GPU hardware memory models are rapidly evolving, and how this directly affects C++ programmers.</li>
</ul>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1784&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2013/02/021113_1851_atomicweapo1.png" medium="image" />
	</item>
		<item>
		<title>Videos: Panel, and C++ Concurrency</title>
		<link>http://herbsutter.com/2013/01/15/videos-panel-and-c-concurrency/</link>
		<comments>http://herbsutter.com/2013/01/15/videos-panel-and-c-concurrency/#comments</comments>
		<pubDate>Wed, 16 Jan 2013 00:20:29 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1707</guid>
		<description><![CDATA[I’m about two weeks late posting this, but two more C++ and Beyond 2012 videos are now available online. The first is my concurrency talk: C++ and Beyond 2012: C++ Concurrency (Herb Sutter) I’ve spoken and written on these topics before. Here’s what’s different about this talk: Brand new: This material goes beyond what I’ve [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1707&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’m about two weeks late posting this, but two more <em><a href="http://cppandbeyond.com/">C++ and Beyond 2012</a></em> videos are now available online.</p>
<p>The first is my concurrency talk:</p>
<blockquote>
<h5><a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism"><img style="background-image:none;float:right;padding-top:0;padding-left:0;display:inline;padding-right:0;border:0;" alt="" src="http://isocpp.org/files/img/cb12-sutter-concurrency.png" width="400" height="259" align="right" border="0" /></a><a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism">C++ and Beyond 2012: C++ Concurrency</a> (Herb Sutter)</h5>
<p>I’ve spoken and written on these topics before. Here’s what’s different about this talk:</p>
<ul>
<li><strong>Brand new:</strong> This material goes beyond what I’ve written and taught about before in my Effective Concurrency articles and courses.</li>
<li><strong>Cutting-edge current:</strong> It covers the best-practices state of the art techniques and shipping tools, and what parts of that are standardized in C++11 already (the answer to that one may surprise you!) and what’s en route to near-term standardization and why, with coverage of the latest discussions.</li>
<li><strong>Blocking vs. non-blocking:</strong> What’s the difference between blocking and non-blocking styles, why on earth would you care, which kinds does C++11 support, and how are we looking at rounding it out in C++1y?</li>
</ul>
<p>The answers all matter to you – even the ones not yet in the C++ standard – because they are real, available in shipping products, and affect how you design your software today.</p></blockquote>
<p>The second is one of the panels:</p>
<blockquote>
<h5><a href="http://channel9.msdn.com/posts/C-and-Beyond-2012-Panel-Convincing-your-Colleagues"><img style="background-image:none;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;display:inline;padding-right:0;border:0;" title="image" alt="image" src="http://herbsutter.files.wordpress.com/2013/01/image1.png?w=400&#038;h=224" width="400" height="224" align="right" border="0" /></a><a href="http://channel9.msdn.com/posts/C-and-Beyond-2012-Panel-Convincing-your-Colleagues">C++ and Beyond 2012: Panel – Convincing your Colleagues</a></h5>
<p>From C++ and Beyond 2012, Andrei, Herb and Scott present Convincing Your Colleagues &#8211; an interactive panel.</p>
<p>Abstract:</p>
<p>You can’t do a better job if you don’t change what you’re doing, but change is hard.  It’s especially hard when what needs to change is your colleagues’ approach to software development. Moving your team forward often requires persuading your peers to change their behavior, sometimes to do something they’re not doing, other times to stop doing something they’ve become accustomed to.  Whether the issue is to embrace or avoid C++ language features, to adopt new development tools or abandon old ones, to increase use of or scale back on overuse of design patterns, to adhere to coding standards, or any of the plethora of other matters that affect software creation, moving things forward typically requires getting your colleagues to buy into the change you’re proposing.  But how can you do that?</p>
<p>In this panel session, Andrei, Herb, and Scott share how they go about convincing their colleagues to change and take questions from the audience.</p></blockquote>
<p>Truth be told, the panel ranged widely and probably most of the time was on other topics!</p>
<p>I hope you find them useful.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1707&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/01/15/videos-panel-and-c-concurrency/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://isocpp.org/files/img/cb12-sutter-concurrency.png" medium="image" />

		<media:content url="http://herbsutter.files.wordpress.com/2013/01/image1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Java vulnerabilities</title>
		<link>http://herbsutter.com/2013/01/15/java-vulnerabilities/</link>
		<comments>http://herbsutter.com/2013/01/15/java-vulnerabilities/#comments</comments>
		<pubDate>Wed, 16 Jan 2013 00:08:30 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1703</guid>
		<description><![CDATA[With the help of friends Robert Seacord and David Svoboda of CERT in particular, I posted a note and link to their CERT post today because people have been misunderstanding the recent Java vulnerabilities, thinking they’re somehow really C or C++ vulnerabilities because Java is implemented in C and C++. From the post: Are the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1703&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.cert.org/blogs/certcc/2013/01/anatomy_of_java_exploits.html"><img style="float:right;margin:0 0 0 10px;display:inline;" alt="" align="right" src="http://isocpp.org/files/img/cert-java-exploit_1.PNG" width="447" height="309" /></a>With the help of friends Robert Seacord and David Svoboda of CERT in particular, I <a href="http://isocpp.org/blog/2013/01/are-the-java-vulnerabilities-actually-c-and-c-vulnerabilities">posted a note</a> and link to their CERT post today because people have been misunderstanding the recent Java vulnerabilities, thinking they’re somehow really C or C++ vulnerabilities because Java is implemented in C and C++.</p>
<p>From the post:</p>
<blockquote><h3><a href="http://isocpp.org/blog/2013/01/are-the-java-vulnerabilities-actually-c-and-c-vulnerabilities">Are the Java vulnerabilities actually C and C++ vulnerabilities?</a></h3>
<p>by Herb Sutter</p>
<p>&#160;</p>
<p>You’ve probably seen the headlines:</p>
</blockquote>
<blockquote><h5><a href="http://www.cert.org/blogs/certcc/2013/01/java_in_web_browser_disable_no.html"><em>[US-CERT] Java in Web Browser: Disable Now!</em></a></h5>
<p><em>We’ve been telling people to disable Java for years. … We have confirmed that VU#625617 can be used to reliably execute code on Windows, OS X, and Linux platforms. And the exploit code for the vulnerability is publicly available and already incorporated into exploit kits. This should be enough motivation for you to turn Java off.</em></p>
<h5><a href="http://dottech.org/92964/firefox-and-apple-have-blocked-java-while-u-s-homeland-security-recommends-everyone-disable-it-because-of-vulnerabilities/"><em>Firefox and Apple have blocked Java while U.S. Homeland Security recommends everyone disable it, because of vulnerabilities</em></a></h5>
<h5><a href="http://news.cnet.com/8301-1009_3-57563951-83/homeland-security-still-advises-disabling-java-even-after-update/"><em>Homeland Security still advises disabling Java, even after update</em></a></h5>
</blockquote>
<blockquote><p>Some people have asked whether last week’s and similar recent Java vulnerabilities are actually C or C++ vulnerabilities – because, like virtually all modern systems software, Java is implemented in C and C++.</p>
<p>The answer is no, these particular exploits are pure Java. Some other exploits have indeed used vulnerabilities in Java’s native C code implementation, but the major vulnerabilities in the news lately are in Java itself, and they enable portable exploits on any operating system with a single program. …</p>
</blockquote>
<p>Some other C++ experts who have better sense than I do won’t add the following bit publicly, but I can’t help myself: Insert “write once, pwn everywhere” joke here…</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/java/'>Java</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1703&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/01/15/java-vulnerabilities/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://isocpp.org/files/img/cert-java-exploit_1.PNG" medium="image" />
	</item>
		<item>
		<title>Video: You Don&#8217;t Know const and mutable</title>
		<link>http://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/</link>
		<comments>http://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/#comments</comments>
		<pubDate>Tue, 01 Jan 2013 17:34:09 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1700</guid>
		<description><![CDATA[At C++ and Beyond in August, I gave a 30 min talk on the changed meaning of const and mutable. The talk video is now online: You Don’t Know [keyword] and [keyword] const means const. Bonus: mutable is useful and continues to mean ‘already as good as const.’ This is another way C++ has become [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1700&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/posts/C-and-Beyond-2012-Herb-Sutter-You-dont-know-blank-and-blank"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2013/01/image.png?w=244&#038;h=139" width="244" height="139" /></a>At <a href="http://cppandbeyond.com">C++ and Beyond</a> in August, I gave a 30 min talk on the changed meaning of const and mutable. The talk video is now online:</p>
<blockquote><h3><font color="#333333"><a href="http://channel9.msdn.com/posts/C-and-Beyond-2012-Herb-Sutter-You-dont-know-blank-and-blank">You Don’t Know [keyword] and [keyword]</a></font></h3>
<p><em>const</em> means <em>const</em>.</p>
<p>Bonus: <em>mutable</em> is useful and continues to mean ‘already as good as <em>const</em>.’</p>
</blockquote>
<p>This is another way C++ has become simpler: <em>const</em> now means what people always thought it meant, and the four-line code example doesn’t need deep analysis at all – it just works.</p>
<p>But we analyze the four-line example anyway as a motivating case to see why and how it works, so we can fully appreciate this new simplification in C++11…</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1700&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2013/01/image.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>An implementation of generic lambdas is now available</title>
		<link>http://herbsutter.com/2012/12/20/an-implementation-of-generic-lambdas-is-now-available/</link>
		<comments>http://herbsutter.com/2012/12/20/an-implementation-of-generic-lambdas-is-now-available/#comments</comments>
		<pubDate>Fri, 21 Dec 2012 02:04:33 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1693</guid>
		<description><![CDATA[For those interested in C++ standardization and not already following along at isocpp.org, here&#8217;s an item of likely interest: An implementation of generic lambdas (request for feedback)—Faisal Vali This week, Faisal Vali shared an initial &#8220;alpha&#8221; implementation of generic lambdas in Clang. Faisal is the lead author of the proposal (N3418), with Herb Sutter and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1693&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><img alt="" src="http://herbsutter.files.wordpress.com/2012/12/122112_0210_animplement1.gif?w=500" align="right" />For those interested in C++ standardization and not already following along at <a href="http://isocpp.org">isocpp.org</a>, here&#8217;s an item of likely interest:</p>
<blockquote><p><a href="http://isocpp.org/blog/2012/12/an-implementation-of-generic-lambdas-request-for-feedback-faisal-vali"><strong>An implementation of generic lambdas (request for feedback)—Faisal Vali</strong></a></p>
<p>This week, Faisal Vali shared an initial &#8220;alpha&#8221; implementation of generic lambdas in Clang. Faisal is the lead author of the proposal (<a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3418.pdf" target="_blank">N3418</a>), with Herb Sutter and Dave Abrahams.</p>
<p>To read and participate in the active discussion, see the <a href="https://groups.google.com/a/isocpp.org/forum/?fromgroups">message thread on std-proposals</a>.</p>
<p>Here is a copy of Faisal&#8217;s announcement…</p></blockquote>
<p><a href="http://isocpp.org/blog/2012/12/an-implementation-of-generic-lambdas-request-for-feedback-faisal-vali">Read more at isocpp.org…</a></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1693&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/12/20/an-implementation-of-generic-lambdas-is-now-available/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/12/122112_0210_animplement1.gif" medium="image" />
	</item>
		<item>
		<title>Compatibility</title>
		<link>http://herbsutter.com/2012/12/04/compatibility/</link>
		<comments>http://herbsutter.com/2012/12/04/compatibility/#comments</comments>
		<pubDate>Tue, 04 Dec 2012 18:06:54 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1691</guid>
		<description><![CDATA[On yesterday’s thread, I just wrote in a comment: @Jon: Yes, C++ is complex and the complexity is largely because of C compatibility. I agree with Bjarne that there’s a small language struggling to get out — I’ve participated in private experiments to specify such a language, and you can do it in well under [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1691&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>On yesterday’s thread, I just wrote in a comment:</p>
<blockquote><p>@Jon: Yes, C++ is complex and the complexity is largely because of C compatibility. I agree with Bjarne that there’s a small language struggling to get out — I’ve participated in private experiments to specify such a language, and you can do it in well under half the complexity of C++ without losing the expressivity and flexibility of C++. However, it does require changes to syntax (mainly) and semantics (secondarily) that amount to making it a new language, which makes it a massive breaking change for programs (where existing code doesn’t compile and would need to be rewritten manually or with a tool) and programmers (where existing developers need retraining). That’s a very big tradeoff. So just as C++ ‘won’ in the 90s because of its own strengths plus its C compatibility, C++11 is being adopted because of its own strengths plus its C++98 compatibility. At the end of the day compatibility continues to be a very strong force and advantage that isn’t lightly tossed aside to “improve” things. However, it’s still worthwhile and some interesting things may come of it. Stay tuned, but expect (possible) news in years rather than months.</p>
</blockquote>
<p>That reminded me of a snippet from the September 2012 issues of CACM. When I first read it, I thought it was so worthwhile that I made a magnified copy and pasted it on the window outside my office at work – it’s still there. The lightly annotated conclusion is shown here.</p>
<p><a href="http://herbsutter.files.wordpress.com/2012/12/image.png"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:10px 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/12/image_thumb.png?w=429&#038;h=1492" width="429" height="1492" /></a>The article itself was about a different technology, but the Lessons Learned conclusion remind us of the paramount importance of two things:</p>
<ul>
<li><strong>Backward compatibility with simple migration path (“compat”). That’s what keeps you “in the ecosystem.”</strong> If you don’t have such compatibility, don’t expect wide adoption unless there are hugely compelling reasons to put up with the breaking change. It’s roughly the same kind of ecosystem change for programmers to go from Language X to Language Y as for users to go from Platform X to Platform Y (e.g., Windows to Mac, iPhone to Android) – in each case you have a lot of relearning, and you lose understood tools and services some of which have replacements and some of which don’t.</li>
<li><strong>Focusing on complete end-to-end solutions (“SFE” or scenario-focused engineering).</strong> This is why it’s important not to ship just a bunch of individual features, because that can leave holes where Steps 1, 2, and 4 of an end-to-end experience are wonderful but Step 3 is awkward, unreliable, or incomplete, which renders much of the good work in the other steps unuseful since they can’t be used as much or possibly at all.</li>
</ul>
<p>Enjoy.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1691&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/12/04/compatibility/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/12/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Perspective: &#8220;Why C++ Is Not &#8216;Back&#8217;&#8221;</title>
		<link>http://herbsutter.com/2012/12/03/perspective-why-c-is-not-back/</link>
		<comments>http://herbsutter.com/2012/12/03/perspective-why-c-is-not-back/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 21:34:30 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C# / .NET]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1684</guid>
		<description><![CDATA[John Sonmez wrote a nice article on the weekend – both the article and the comments are worth reading. “Why C++ Is Not ‘Back’” by John Sonmez I love C++. […] There are plenty of excellent developers I know today that still use C++ and teach others how to use it and there is nothing [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1684&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://simpleprogrammer.com/2012/12/01/why-c-is-not-back/"><img style="float:right;margin:0 0 10px 10px;display:inline;" alt="" src="http://complextosimple.files.wordpress.com/2012/12/announcer_thumb.jpg?w=229&#038;h=240" height="240" width="229" /></a>John Sonmez wrote a nice article on the weekend – both the article and the comments are worth reading.</p>
<blockquote>
<h3><a href="http://simpleprogrammer.com/2012/12/01/why-c-is-not-back/">“Why C++ Is Not ‘Back’”</a></h3>
<p><em>by John Sonmez</em></p>
<p>I love C++. […] There are plenty of excellent developers I know today that still use C++ and teach others how to use it and there is nothing at all wrong with that.</p>
<p>So what is the problem then?</p>
<p>[…] Everyone keeps asking me if they need to learn C++, but just like my answer was a few years ago, it is the same today—NO!</p>
<p>Ok, so “NO” in caps is a bit harsh.  A better answer is “why?”</p>
<p>[…]</p></blockquote>
<p>Although I don’t agree with everything John says, he presents something quite valuable, and unfortunately rare: a <em>thoughtful hype-free opinion</em>. This is valuable especially when (not just “even when”) it differs from your own opinion, because combining different thoughtful views of the same thing gives something exceedingly important and precious: <em>perspective</em>.</p>
<p>By definition, depth perception is something you get from seeing and combining more than one point of view. This is why one of my favorite parts of any conference or group interview is discussions between experts on points where they disagree – because experts do regularly disagree, and when they each present their thoughtful reasons and qualifications and specific cases (not just hype), you get to see <em>why</em> a point is valid, <em>when</em> it is valid and not valid, <em>how</em> it applies to a specific situation or doesn’t, and so on.</p>
<p>I encourage you to read the article and the comments. This quote isn’t the only thing I don’t fully agree with, but it’s the one thing I’ll respond to a little from the article:</p>
<blockquote><p>There are only about three sensible reasons to learn C++ today that I can think of.</p></blockquote>
<p>There are other major reasons in addition to those, such as:</p>
<ul>
<li><em>Servicing</em>, which is harder when you depend on a runtime.</li>
<li><em>Testing</em>, since you lose the ability to test your entire application (compare doing all-static or mostly-static linking with having your application often be compiled/jitted for the first time on an end user’s machine).</li>
</ul>
<p>These aren’t bad things in themselves, just tradeoffs and reasons to prefer native code vs managed code depending on your application’s needs.</p>
<p>But even the three points John does mention are very broad reasons that apply often, especially the issue of control over memory layouts, to the point where I would say: <strong>In any language, if you are serious about performance you will be using arrays a lot (not “always,” just “a lot”). </strong>Some languages make that easier and give you much better control over layout in general and arrays in particular, while other languages/environments make it harder (possible! but harder) and you have to “opt out” or &#8220;work against&#8221; the language’s/runtime’s strong preference for pointer-chasing node-based data structures.</p>
<p>For more, please see also my April 2012 Lang.NEXT talk <strong><a href="http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/-Not-Your-Father-s-C-">“(Not Your Father’s) C++”</a></strong>, especially the second half:</p>
<ul>
<li>From <strong>19:20</strong>, I try to contrast the <strong>value and tenets of C++ and of managed language/environments</strong>, including that each is making a legitimate and useful design choice.</li>
<li>From <strong>36:00</strong>, I try to address the question of: “<strong>can managed languages do essentially everything</strong> that’s interesting, so native C/C++ code should be really just for things like device drivers?”</li>
<li>From <strong>39:00</strong>, I talk about <strong>when each one is valuable and should be used</strong>, especially that if programmer time is your biggest cost, that’s what you should optimize for and it’s exactly what managed languages/environments are designed for.</li>
</ul>
<p>But again, I encourage you to read John’s article – <em>and the comments</em> – yourself. There’s an unusually high signal-to-noise ratio here.</p>
<p>It’s always nice to encounter a thoughtful balanced piece of writing, whether or not we agree with every detail. Thanks, John!</p>
<br />Filed under: <a href='http://herbsutter.com/category/c-net/'>C# / .NET</a>, <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1684&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/12/03/perspective-why-c-is-not-back/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2012/12/announcer_thumb.jpg" medium="image" />
	</item>
		<item>
		<title>&#8220;256 cores by 2013&#8221;?</title>
		<link>http://herbsutter.com/2012/11/30/256-cores-by-2013/</link>
		<comments>http://herbsutter.com/2012/11/30/256-cores-by-2013/#comments</comments>
		<pubDate>Sat, 01 Dec 2012 02:12:29 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1679</guid>
		<description><![CDATA[I just saw a tweet that’s worth commenting on: Almost right, and we have already reached that. I said something similar to the above, but with two important differences: I said hardware “threads,” not only hardware “cores” – it was about the amount of hardware parallelism available on a mainstream system. What I gave was [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1679&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I just saw a tweet that’s worth commenting on:</p>
<p><a href="http://herbsutter.files.wordpress.com/2012/11/image3.png"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:none;padding-top:0;padding-left:0;margin:0 auto 10px;border-left:0;display:block;padding-right:0;" border="0" alt="image" src="http://herbsutter.files.wordpress.com/2012/11/image_thumb.png?w=513&#038;h=146" width="513" height="146" /></a></p>
<p>Almost right, and we have already reached that.</p>
<p>I said something similar to the above, but with two important differences:</p>
<ol>
<li>I said hardware “threads,” not only hardware “cores” – it was about the <strong>amount of hardware parallelism </strong>available on a mainstream system. </li>
<li>What I gave was a min/max <strong>range estimate of roughly 16 to 256 (the latter being threads)</strong> under different sets of assumptions. </li>
</ol>
<p>So: Was I was right about 2013 estimates?</p>
<p>Yes, pretty much, and in fact we already reached or exceeded that in 2011 and 2012:</p>
<ul>
<li>Lower estimate line: In 2011 and 2012 parts, Intel Core i7 Sandy Bridge and Ivy Bridge are delivering almost the expected lower baseline, and offering 8-way and 12-way parallelism = 4-6 cores x 2 hardware threads per core. </li>
<li>Upper estimate line: In 2012, as mentioned in the article (which called it Larrabee, now known as MIC or Xeon Phi) is delivering 200-way to 256-way parallelism = 50-64 cores x 4 hardware threads per core. Also, in 2011 and 2012, GPUs have since emerged into more mainstream use for computation (GPGPU), and likewise offer massive compute parallelism, such as 1,536-way parallelism on a machine having a single NVidia Tesla card. </li>
</ul>
<p>Yes, mainstream machines do in fact have examples of both ends of the “16 to 256 way parallelism” range. And beyond the upper end of the range, in fact, for those with higher-end graphics cards.</p>
<p>For more on these various kinds of compute cores and threads, see also my article <strong><a href="http://herbsutter.com/welcome-to-the-jungle/">Welcome to the Jungle</a></strong>.</p>
<p>&#160;</p>
<p>Longer answer follows:</p>
<p>Here’s the main part from article, <a href="http://www.drdobbs.com/parallel/design-for-manycore-systems/219200099?pgno=3"><strong>“Design for Manycore Systems”</strong></a> (August 11, 2009). Remember this was written over three years ago – in the Time Before iPad, when Android was under a year old:</p>
<blockquote><h3><font style="font-weight:normal;">How Much Scalability Does Your Application Need?</font></h3>
<p>So how much parallel scalability should you aim to support in the application you‘re working on today, assuming that it&#8217;s compute-bound already or you can add killer features that are compute-bound and also amenable to parallel execution? The answer is that <strong>you want to match your application&#8217;s scalability to the amount of hardware parallelism in the target hardware that will be available during your application&#8217;s expected production or shelf lifetime. As shown in Figure 4, that equates to the number of hardware threads you expect to have on your end users&#8217; machines.</strong> </p>
<p align="center"><img src="http://twimgs.com/ddj/images/article/2009/0908/090811ec_f4.gif" /></p>
<p align="center"><b>Figure 4</b>: How much concurrency does your program need in order to exploit given hardware? </p>
<p>Let&#8217;s say that YourCurrentApplication 1.0 will ship next year (mid-2010), and you expect that it&#8217;ll be another 18 months until you ship the 2.0 release (early 2012) and probably another 18 months after that before most users will have upgraded (mid-2013). Then you&#8217;d be interested in judging what will be the likely mainstream hardware target up to mid-2013. </p>
<p><strong>If we stick with &quot;just more of the same&quot;</strong> as in Figure 2&#8242;s extrapolation, we&#8217;d expect aggressive early hardware adopters to be running 16-core machines (possibly double that if they&#8217;re aggressive enough to run dual-CPU workstations with two sockets), and <strong>we&#8217;d likely expect most general mainstream users to have 4-, 8- or maybe a smattering of 16-core machines</strong> (accounting for the time for new chips to be adopted in the marketplace). <em><font color="#c0504d">[[Note: I often get lazy and say “core” to mean all hardware parallelism. In context above and below, it’s clear we’re talking about “cores and threads.”]]</font></em></p>
<p>But what if the gating factor, parallel-ready software, goes away? Then CPU vendors would be free to take advantage of <strong>options like the one-time 16-fold hardware parallelism jump</strong> illustrated in Figure 3, and we get an envelope like that shown in Figure 5. </p>
<p><img style="float:none;margin-left:auto;display:block;margin-right:auto;" src="http://twimgs.com/ddj/images/article/2009/0908/090811ec_f5.gif" /></p>
<p align="center"><b>Figure 5</b>: Extrapolation of “more of the same big cores” and “possible one-time switch to 4x smaller cores plus 4x threads per core” (not counting some transistors being used for other things like on-chip GPUs). </p>
</blockquote>
<p>First, let’s look at the lower baseline, ‘most general mainstream users to have [4-16 way parallelism] machines in 2013’? So where are were in 2012 today for mainstream CPU hardware parallelism? Well, Intel Core i7 (e.g., Sandy Bridge, Ivy Bridge) are typically in the 4 to 6 core range – which, <strong>with hyperthreading == hardware threads, means 8 to 12 hardware threads</strong>.</p>
<p>Second, what about the higher potential line for 2013? As noted above:</p>
<ul>
<li>Intel’s Xeon Phi (then Larrabee) is now delivering 50-64 cores x 4 threads = 200 to 256-way parallelism. That’s no surprise, because this article’s upper line was based on exactly the Larrabee data point (see quote below). </li>
<li>GPUs already blow the 256 upper bound away – any machine with a two-year-old Tesla has 1,536-way parallelism for programs (including mainstream programs like DVD encoders) that can harness the GPU. </li>
</ul>
<p>So not only did we already reach the 2013 upper line early, in 2012, but we already exceeded it for applications that can harness the GPU for computation.</p>
<p>As I said in the article:</p>
<blockquote><p>I don&#8217;t believe either the bottom line or the top line is the exact truth, but as long as sufficient parallel-capable software comes along, the truth will probably be somewhere in between, especially if we have processors that offer a mix of large- and small-core chips, or that use some chip real estate to bring GPUs or other devices on-die. That&#8217;s more hardware parallelism, and sooner, than most mainstream developers I&#8217;ve encountered expect. </p>
<p>Interestingly, though, we already noted two current examples: Sun&#8217;s Niagara, and Intel&#8217;s Larrabee, already provide double-digit parallelism in mainstream hardware via smaller cores with four or eight hardware threads each. <strong>&quot;Manycore&quot; chips, or perhaps more correctly &quot;manythread&quot; chips, are just waiting to enter the mainstream</strong>. Intel could have built a nice 100-core part in 2006. The gating factor is the software that can exploit the hardware parallelism; that is, the gating factor is you and me. </p>
</blockquote>
<br />Filed under: <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1679&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/30/256-cores-by-2013/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/11/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://twimgs.com/ddj/images/article/2009/0908/090811ec_f4.gif" medium="image" />

		<media:content url="http://twimgs.com/ddj/images/article/2009/0908/090811ec_f5.gif" medium="image" />
	</item>
		<item>
		<title>Podcast: Interview on Hanselminutes</title>
		<link>http://herbsutter.com/2012/11/24/podcast-interview-on-hanselminutes/</link>
		<comments>http://herbsutter.com/2012/11/24/podcast-interview-on-hanselminutes/#comments</comments>
		<pubDate>Sun, 25 Nov 2012 00:20:02 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1674</guid>
		<description><![CDATA[A few weeks ago at the Build conference, Scott Hanselman and I sat down to talk about C++ and modern UI/UX. The podcast is now live here: The Hanselminutes Podcast, Show #346 “Why C++” with Herb Sutter Topics Scott raises include: 2:00 Scott mentions he has used C++ in the past. C++ has changed. We [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1674&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.hanselminutes.com/346/why-c-with-herb-sutter"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/11/image2.png?w=364&#038;h=90" width="364" height="90" /></a>A few weeks ago at the Build conference, Scott Hanselman and I sat down to talk about C++ and modern UI/UX. The podcast is now live here:</p>
<blockquote><p><font color="#333333">The Hanselminutes Podcast, Show #346       <br /><a href="http://www.hanselminutes.com/346/why-c-with-herb-sutter"><strong>“Why C++” with Herb Sutter</strong></a></font></p>
</blockquote>
<p>Topics Scott raises include:</p>
<ul>
<li><strong>2:00</strong> Scott mentions he has used C++ in the past. C++ has changed. We still call it C++, but it’s a very different language now.</li>
<li><strong>5:30</strong> (Why) do we care about performance any more?</li>
<li><strong>10:00</strong> What’s this GPGPU thing? Think of your GPU as your modern 80387.</li>
<li><strong>13:45</strong> C++ is having a resurgence. Where is C++ big?</li>
<li><strong>18:00</strong> Why not just use one language? or, What is C++ good at? Efficient abstraction and portability.</li>
<li><strong>21:45</strong> Programmers have a responsibility to support the business. Avoid the pitfall of speeds &amp; feeds.</li>
<li><strong>24:00</strong> My experience with my iPad, my iPhone, and my Slate 7 with Win8.</li>
<li><strong>28:45</strong> We’re in two election seasons – (a) political and (b) technology (Nexus, iPad Mini, Surface, …). Everyone is wallpapering the media with ads (some of them attack ads), and vying for customer votes/$$, and seeing who’s going to be the winner.</li>
<li><strong>35:00</strong> Natural user interfaces – we get so easily used to touch that we paw all screen, and Scott’s son gets so used to saying “Xbox pause” that anything that doesn’t respond is “broken.”</li>
</ul>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1674&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/24/podcast-interview-on-hanselminutes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/11/image2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Reader Q&amp;A: A good book to learn C++11?</title>
		<link>http://herbsutter.com/2012/11/20/reader-qa-a-good-book-to-learn-c11/</link>
		<comments>http://herbsutter.com/2012/11/20/reader-qa-a-good-book-to-learn-c11/#comments</comments>
		<pubDate>Tue, 20 Nov 2012 17:26:22 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1667</guid>
		<description><![CDATA[Last night a reader asked one of the questions that helped motivate the creation of isocpp.org: I am trying to learn the new C++. I am wondering if you are aware of resources or courses that can help me learn a little. I was not able to find any books for C++11. Any help would [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1667&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://isocpp.org"><img style="float:right;margin:0 0 10px 10px;display:inline;" align="right" src="http://isocpp.org/images/uploads/logo-sun.jpg" width="188" height="104" /></a>Last night a reader asked one of the questions that helped motivate the creation of isocpp.org:</p>
<blockquote><p>I am trying to learn the new C++. I am wondering if you are aware of resources or courses that can help me learn a little. I was not able to find any books for C++11. Any help would be greatly appreciated. </p>
<p>By the way, the isocpp website is great :)</p>
</blockquote>
<p>Thanks! And you beat me to the punchline. :)</p>
<p>A good place to start is <a href="http://isocpp.org/get-started">isocpp.org/get-started</a>. It recommends four books, three of which have been updated for C++11 (and two of those three are available now). C++ Primer 5e is a good choice.</p>
<p>We also maintain a list of new articles and books under <a href="http://isocpp.org/blog/category/articles-books">isocpp.org/blog/category/articles-books</a>.</p>
<p>As for courses, there’s also a growing list of good courses there under <a href="http://isocpp.org/blog/category/training">isocpp.org/blog/category/training</a>, including two C++11 overview courses by Scott Meyers and Dave Abrahams respectively.</p>
<p>As with all blog categories, you have three ways to find the most recent items under Articles &amp; Books, Training, and other categories:</p>
<ul>
<li>Home page: The most recent items in each category are always listed right on the site’s newspaper-inspired home page.</li>
<li>RSS: You can subscribe to RSS feeds for all posts, or for specific categories to get notifications of new articles, books, training, events, and more as they become available.</li>
<li>Twitter: Follow <a href="https://twitter.com/isocpp"><strong>@isocpp</strong></a> for notifications of new stuff.</li>
</ul>
<p>The site and blog are curated, aiming for higher quality and lower volume. Even so, we know you won’t be able to read, watch, or listen to all of the content. So we’re doing our best to make sure that when you do pick something recommended by the site, it’s likely to be of high quality and address what you’re looking to find.</p>
<p>Enjoy! This is version 1 of the site… I hope that it’s already useful, and you’ll see quite a bit more over the coming year.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1667&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/20/reader-qa-a-good-book-to-learn-c11/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://isocpp.org/images/uploads/logo-sun.jpg" medium="image" />
	</item>
		<item>
		<title>Friday&#8217;s Q&amp;A session now online</title>
		<link>http://herbsutter.com/2012/11/06/fridays-qa-session-now-online/</link>
		<comments>http://herbsutter.com/2012/11/06/fridays-qa-session-now-online/#comments</comments>
		<pubDate>Tue, 06 Nov 2012 21:11:12 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1665</guid>
		<description><![CDATA[My live Q&#38;A after Friday’s The Future of C++ talk is now online on Channel 9. The topics revolved around… … recent progress and near-future directions for C++, both at Microsoft and across the industry, and talks about some announcements related to C++11 support in VC++ 2012 and the formation of the Standard C++ Foundation. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1665&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Events/Ch9Live/Channel-9-Live-at-BUILD-2012/Herb-Sutter-at-Build-2012"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/11/image.png?w=239&#038;h=139" width="239" height="139" /></a>My live Q&amp;A after Friday’s The Future of C++ talk is <a href="http://channel9.msdn.com/Events/Ch9Live/Channel-9-Live-at-BUILD-2012/Herb-Sutter-at-Build-2012">now online on Channel 9</a>. The topics revolved around…</p>
<blockquote><p>… recent progress and near-future directions for C++, both at Microsoft and across the industry, and talks about some announcements related to C++11 support in VC++ 2012 and the formation of the <a href="http://isocpp.org/about">Standard C++ Foundation</a>.</p>
<p>Herb takes questions from a live virtual audience and demos the new <a href="http://isocpp.org/">http://isocpp.org</a> site on an 82 inch Perceptive Pixel display attached to a Windows 8 machine.</p>
</blockquote>
<p>Thanks to everyone who tuned in.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1665&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/06/fridays-qa-session-now-online/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/11/image.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Our industry is young again, and it&#8217;s all about UI</title>
		<link>http://herbsutter.com/2012/11/03/our-industry-is-young-again-and-its-all-about-ui/</link>
		<comments>http://herbsutter.com/2012/11/03/our-industry-is-young-again-and-its-all-about-ui/#comments</comments>
		<pubDate>Sat, 03 Nov 2012 23:12:50 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[Friday Thoughts]]></category>
		<category><![CDATA[Opinion & Editorial]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1647</guid>
		<description><![CDATA[Jeff Atwood’s post two days ago inspired me to write this down. Thanks, Jeff. “I can&#8217;t even remember the last time I was this excited about a computer.” – Jeff Atwood, November 1, 2012 Our industry is young again, full of the bliss and sense of wonder and promise of adventure that comes with youth. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1647&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Jeff Atwood’s post two days ago inspired me to write this down. Thanks, Jeff.</p>
<blockquote><p><em>“I can&#8217;t even remember the last time I was this excited about a computer.”</em></p>
<p>– <a href="http://www.codinghorror.com/blog/2012/11/do-you-wanna-touch.html">Jeff Atwood, November 1, 2012</a></p></blockquote>
<hr />
<p>Our industry is young again, full of the bliss and sense of wonder and promise of adventure that comes with youth.</p>
<p><strong>Computing feels young and fresh</strong> in a way that it hasn’t felt for years, and that has only happened to this degree at two other times in its history. Many old-timers, including myself, have said “this feels like 1980 again.”</p>
<p>It does indeed. And the reason why is all about user interfaces (UI).</p>
<h2>Wave 1: Late 1950s through 60s</h2>
<p>First, computing felt young in the late 1950s through the 60s because it <em>was</em> young, and made computers personally available to a select few people. Having computers at all was new, and the ability to make a machine <em>do </em>things opened up a whole new world for a band of pioneers like Dijkstra and Hoare, and <a href="http://en.wikipedia.org/wiki/Spacewar!"><strong>Russell (Spacewar!)</strong></a> and <a href="http://herbsutter.com/2009/01/08/answer-to-16-technologies-engelbart-and-the-mother-of-all-demos/"><strong>Engelbart (Mother of All Demos)</strong></a> who made these computers personal for at least a few people.</p>
<p>The machines were useful. But the excitement came from <em>personally interacting</em> with the machine.</p>
<h2>Wave 2: Late 1970s through 80s</h2>
<p>Second, computing felt young again in the late 1970s and 80s. Then, truly personal single-user computers were new. They opened up to a far wider audience the sense of wonder that came with having a computer of our very own, and often even with a colorful graphical interface to draw us into its new worlds. I’ll include <strong><a href="http://en.wikipedia.org/wiki/Colossal_Cave_Adventure">Woods and Crowther (ADVENT)</a></strong> as an example, because they used a PDP as a personal computer (smile) and their game and many more like it took off on the earliest true PCs – Exidy Sorcerers and TRS-80s, Ataris and Apples. This was the second and much bigger wave of delivering computers we could personally interact with.</p>
<p>The machines were somewhat useful; people kept trying to justify paying $1,000 for one “to organize recipes.” (Really.) But the real reason people wanted them was that they were more intimate – the excitement once again came from <em>personally interacting </em>with the machine.</p>
<h2>Non-wave: 1990s through mid-2000s</h2>
<p>Although WIMP interfaces proliferated in the 1990s and did deliver benefits and usability, they were never as exciting to the degree computers were in the 80s. Why not? Because they weren’t nearly as transformative in making computers more <em>personal</em>, more fun. And then, to add insult to injury, once we shipped WIMPiness throughout the industry, we called it good for a decade and innovation in user interfaces stagnated.</p>
<p>I heard many people wonder whether computing was done, whether this was all there would be. Thanks, Apple, for once again taking the lead in proving them wrong.</p>
<h2>Wave 3: Late 2000s through the 10s</h2>
<p>Now, starting in the late 2000s and through the 10s, modern mobile computers are new and more personal than ever, and they’re just getting started. But what makes them so much more personal? There are three components of the new age of computing, and they’re all about UI (user interfaces)… count ’em:</p>
<ol>
<li>Touch.</li>
<li>Speech.</li>
<li>Gestures.</li>
</ol>
<p>Now don’t get me wrong, these are in addition to keyboards and accurate pointing (mice, trackpads) and writing (pens), not instead of them. I don’t believe for a minute that keyboards and mice and pens are going away, because they’re incredibly useful – I agree with <a href="http://joey.hess.usesthis.com/">Joey Hess</a> (HT to @codinghorror):</p>
<blockquote><p><em>“If it doesn’t have a keyboard, I feel that my thoughts are being forced out through a straw.”</em></p></blockquote>
<p>Nevertheless, touch, speech, and gestures are clearly important. Why? Because <strong>interacting with touch and speech and gestures is how we’re made, and that’s what lets these interactions power a new wave of making computers more personal.</strong> All three are coming to the mainstream in about that order…</p>
<h2>Four predictions</h2>
<p>… and all three aren’t done, they’re just getting started, and we can now see that <strong>at least the first two are inevitable</strong>. Consider:</p>
<p>Touchable screens on smartphones and tablets is just the beginning. <a href="http://www.codinghorror.com/blog/2012/11/do-you-wanna-touch.html">Once we taste the ability to touch any screen, we immediately want and expect all screens to respond to touch.</a> One year from now, when more people have had a taste of it, no one will question whether notebooks and monitors should respond to touch – though maybe a few will still question touch televisions. Two years from now, <strong>we’ll just assume that every screen should be touchable</strong>, and soon we’ll forget it was ever any other way. Anyone set on building non-touch mainstream screens of any size is on the wrong side of history.</p>
<p>Speech recognition on phones and in the living room is just the beginning. This week I recorded a podcast with <a href="http://www.hanselman.com/blog/">Scott Hanselman</a> which will air in another week or two, when Scott shared something he observed firsthand in his son: Once a child experiences saying “Xbox Pause,” he will <strong>expect all entertainment devices to respond to speech commands</strong>, and if they don’t they’re “broken.” Two years from now, speech will probably be the norm as one way to deliver primary commands. (Insert <a href="http://www.youtube.com/watch?v=hShY6xZWVGE">Scotty joke</a> here.)</p>
<p>Likewise, gestures to control entertainment and games in the living room is just the beginning. Over the past year or two, when giving talks I’ve sometimes enjoyed messing with audiences by “changing” a PowerPoint slide by gesturing in the air in front of the screen while really changing the slide with the remote in my pocket. I immediately share the joke, of course, and we all have a laugh together, but the <strong>audience members more and more often just think it’s a new product and expect it to work</strong>. Gestures aren’t just for <a href="http://en.wikipedia.org/wiki/Minority_Report_(film)">John Anderton</a> any more.</p>
<p>Bringing touch and speech and gestures to all devices is a thrilling experience. They are just the beginning of the new wave that’s still growing. And this is the most personal wave so far.</p>
<p>This is an exciting and wonderful time to be part of our industry.</p>
<p>Computing is being reborn, again; <a href="http://www.youtube.com/watch?v=Sv6dMFF_yts">we are young</a> again.</p>
<br />Filed under: <a href='http://herbsutter.com/category/friday-thoughts/'>Friday Thoughts</a>, <a href='http://herbsutter.com/category/opinion-editorial/'>Opinion &amp; Editorial</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1647&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/03/our-industry-is-young-again-and-its-all-about-ui/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Talk now online: The Future of C++ (VC++, ISO C++)</title>
		<link>http://herbsutter.com/2012/11/03/talk-now-online-the-future-of-c-vc-iso-c/</link>
		<comments>http://herbsutter.com/2012/11/03/talk-now-online-the-future-of-c-vc-iso-c/#comments</comments>
		<pubDate>Sat, 03 Nov 2012 22:06:31 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1643</guid>
		<description><![CDATA[Yesterday, many thousands of you were in the room or live online for my talk on The Future of C++. The talk is now available online. This has been a phenomenal year for C++, since C++11’s publication just 12 months ago. And yesterday was a great day for C++. Yesterday I had the privilege of [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1643&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Events/Build/2012/2-005"><img style="float:right;display:inline;" title="image" alt="image" src="http://herbsutter.files.wordpress.com/2012/10/image_thumb.png?w=244&#038;h=139&#038;h=139" height="139" width="244" /></a>Yesterday, many thousands of you were in the room or live online for my talk on The Future of C++. <a href="http://channel9.msdn.com/Events/Build/2012/2-005">The talk is now available online.</a></p>
<p>This has been a phenomenal year for C++, since C++11’s publication just 12 months ago. And yesterday was a great day for C++.</p>
<p>Yesterday I had the privilege of announcing much of what Microsoft and the industry have been working on over the past year.</p>
<h2>(minor) C++ at Microsoft</h2>
<p>On September 12, we shipped VC++ 2012 with the complete C++11 standard library, and adding support for C++11 range-<em>for</em>, <em>enum class</em>, <em>override </em>and <em>final</em>. Less than two months later, yesterday we announced and shipped the November 2012 CTP, a compiler add-in to VC++ 2012 adding C++11 variadic templates, uniform initialization and <em>initializer_list</em>s, delegating constructors, function template default arguments, explicit conversion operators, and raw string literals. <a href="http://blogs.msdn.com/b/vcblog/archive/2012/11/02/visual-c-c-11-and-the-future-of-c.aspx"><strong>Details here</strong></a>, and <a href="http://aka.ms/vc-ctp"><strong>download here</strong></a>.</p>
<p>Note that this is just the first batch of additional C++11 features. Expect further announcements and deliveries in the first half of 2013.</p>
<h2>(major) C++ across the industry</h2>
<p>Interest and investment in C++ continues to accelerate across the software world.</p>
<ul>
<li>ISO C++ standardization is <strong><a href="http://isocpp.org/std/status">accelerating</a></strong>. Major companies are dedicating more people and resources to C++ standardization than they have in years. Over the next 24 months, we plan to ship three Technical Specifications and a new C++ International Standard.</li>
<li>C++ now has a home on the web at <a href="http://isocpp.org"><strong>isocpp.org</strong></a>. Launched yesterday, it both aggregates the best C++ content and hosts new content itself, including Bjarne Stroustrup’s new <a href="http://isocpp.org/tour">Tour of C++</a> and Scott Meyers’ new <a href="http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers">Universal References article</a>.</li>
<li>We now have a <a href="http://isocpp.org/about"><strong>Standard C++ Foundation</strong></a>. Announced yesterday, it is already funded by the largest companies in the industry down to startups, financial institutions to universities, book publishers to other consortia, with more members joining weekly. For the first time in C++’s history since AT&amp;T relinquished control of the language, we have an entity – a trade organization – that exists exclusively to promote Standard C++ on all compilers and platforms, and companies are funding it because the world runs on C++, and investing in Standard C++ is good business.</li>
</ul>
<p><a href="http://herbsutter.com/2012/11/03/our-industry-is-young-again-and-its-all-about-ui/">This is an exciting time to be part of our industry</a>, on any OS and using any language. It’s especially an exciting time to be involved with C++ on all compilers and platforms.</p>
<p>Thank you all, whatever platform and language you use, for being part of it.</p>
<p>Links:</p>
<ul>
<li><a href="http://blogs.msdn.com/b/vcblog/archive/2012/11/02/visual-c-c-11-and-the-future-of-c.aspx">VC++ November 2012 CTP announcement</a></li>
<li><a href="http://blogs.msdn.com/b/vcblog/archive/2012/11/02/from-build-herb-sutter-announces-november-ctp-isocpp-org-standard-c-foundation-and-more.aspx">Broad C++ news release covering the CTP, standardization, site, and Foundation</a></li>
<li><a href="http://channel9.msdn.com/Events/Build/2012/2-005">My talk yesterday covering these announcements</a></li>
</ul>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1643&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/11/03/talk-now-online-the-future-of-c-vc-iso-c/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/10/image_thumb.png?w=244&#38;h=139" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>90 seconds @Build: &#8220;It&#8217;s a great week for C++&#8221;</title>
		<link>http://herbsutter.com/2012/10/31/90-seconds-build-its-a-great-week-for-c/</link>
		<comments>http://herbsutter.com/2012/10/31/90-seconds-build-its-a-great-week-for-c/#comments</comments>
		<pubDate>Wed, 31 Oct 2012 21:56:58 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1641</guid>
		<description><![CDATA[A few hours ago I sat down to give a short teaser for my webcast talk this Friday. Here it is. Feel free to forward. (I don’t think they believed me when I said I could keep it to under two minutes.) Filed under: C++, Microsoft, Software Development, Talks &#38; Events<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1641&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A few hours ago I sat down to give a short teaser for <a href="http://herbsutter.com/2012/10/29/the-future-of-c-live-broadcast-this-friday/">my webcast talk this Friday</a>.</p>
<p>Here it is. Feel free to forward.</p>
<p>(I don’t think they believed me when I said I could keep it to under two minutes.)</p>
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='500' height='312' src='http://www.youtube.com/embed/VWf01ECulHM?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1641&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/10/31/90-seconds-build-its-a-great-week-for-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>The Future of C++: Live broadcast this Friday</title>
		<link>http://herbsutter.com/2012/10/29/the-future-of-c-live-broadcast-this-friday/</link>
		<comments>http://herbsutter.com/2012/10/29/the-future-of-c-live-broadcast-this-friday/#comments</comments>
		<pubDate>Mon, 29 Oct 2012 16:35:29 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1636</guid>
		<description><![CDATA[In my talk on Friday, there will be announcements of broad interest to C++ developers on all compilers and platforms. Please help spread the word. The Future of C++ Friday, November 2, 2012 12:45pm (U.S. Pacific Time) This talk will give an update on recent progress and near-future directions for C++, both at Microsoft and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1636&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Events/Build/2012/2-005"><img style="background-image:none;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;display:inline;padding-right:0;border:0;" title="image" alt="image" src="http://herbsutter.files.wordpress.com/2012/10/image_thumb.png?w=244&#038;h=139" height="139" width="244" /></a>In my talk on Friday, there will be announcements of broad interest to C++ developers on all compilers and platforms. Please help spread the word.</p>
<blockquote>
<h3><strong><a href="http://channel9.msdn.com/Events/Build/2012/2-005">The Future of C++</a></strong></h3>
<p><strong>Friday, November 2, 2012<br />
<a href="http://www.timeanddate.com/worldclock/fixedtime.html?iso=20121102T1945">12:45pm (U.S. Pacific Time)</a></strong></p>
<p>This talk will give an update on recent progress and near-future directions for C++, both at Microsoft and across the industry, with some announcements of interest in both areas. The speaker is the lead language architect of Visual C++ and chair of the ISO C++ committee.</p></blockquote>
<p>The talk will be <a href="http://channel9.msdn.com/">webcast live on Channel 9</a>, and <a href="http://channel9.msdn.com/Events/Build/2012/2-005">available soon afterwards on demand</a>.</p>
<p>If you know people who are interested in C++, on any platform, you’ll want to let them know to tune in.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1636&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/10/29/the-future-of-c-live-broadcast-this-friday/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/10/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Reader Q&amp;A: volatile (again)</title>
		<link>http://herbsutter.com/2012/10/16/reader-qa-volatile-again/</link>
		<comments>http://herbsutter.com/2012/10/16/reader-qa-volatile-again/#comments</comments>
		<pubDate>Tue, 16 Oct 2012 15:53:44 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Effective Concurrency]]></category>
		<category><![CDATA[Reader Q&A]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1631</guid>
		<description><![CDATA[Sarmad Asgher asked a variant of a perennial question: I am implementing multi producer single consumer problem. I have shared variables like m_currentRecordsetSize which tells the current size of the buffer. I am using m_currentRecordsetSize in a critical section do i need to declare it as volatile. If you’re in C or C++, and the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1631&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Sarmad Asgher asked a variant of a perennial question:</p>
<blockquote><p>I am implementing multi producer single consumer problem. I have shared variables like m_currentRecordsetSize which tells the current size of the buffer. I am using m_currentRecordsetSize in a critical section do i need to declare it as volatile.</p>
</blockquote>
<p>If you’re in C or C++, and the variable is not already being protected by a mutex or similar, then you need to declare it <em>atomic</em> (e.g., if it’s an <em>int</em>, then <em>atomic_int</em> in C or <em>atomic&lt;int&gt;</em> in C++. Not <em>volatile</em>.</p>
<blockquote><p>Also is there any article by you on this topic. Please do reply.</p>
</blockquote>
<p>There is! See my article <a href="http://herbsutter.com/2009/01/12/effective-concurrency-volatile-vs-volatile/"><strong>“volatile vs. volatile”</strong></a> for the difference and why C/C++ <em>volatile</em> has nothing to do with inter-thread communication.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/effective-concurrency/'>Effective Concurrency</a>, <a href='http://herbsutter.com/category/reader-qa/'>Reader Q&amp;A</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1631&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/10/16/reader-qa-volatile-again/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>CTP of Windows XP Targeting with C++ in Visual Studio 2012</title>
		<link>http://herbsutter.com/2012/10/09/ctp-of-windows-xp-targeting-with-c-in-visual-studio-2012/</link>
		<comments>http://herbsutter.com/2012/10/09/ctp-of-windows-xp-targeting-with-c-in-visual-studio-2012/#comments</comments>
		<pubDate>Tue, 09 Oct 2012 16:59:14 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1627</guid>
		<description><![CDATA[The three by-far-most-requested “missing features” from Visual C++ 2012 were: Conformance: Keep adding more C++11 language conformance features. XP Targeting: Deliver the ability to build applications that could run on Windows XP, as well as Windows Vista, 7, and 8. Desktop Express: Deliver a free VC++ Express compiler that can be used to create traditional [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1627&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The three by-far-most-requested “missing features” from Visual C++ 2012 were:</p>
<ol>
<li><strong>Conformance:</strong> Keep adding more C++11 language conformance features.</li>
<li><strong>XP Targeting:</strong> Deliver the ability to build applications that could run on Windows XP, as well as Windows Vista, 7, and 8.</li>
<li><strong>Desktop Express:</strong> Deliver a free VC++ Express compiler that can be used to create traditional Windows desktop apps, not just Windows Store apps.</li>
</ol>
<p>Over the spring and summer, we promised to address these “soon after VC++ 2012 ships.”</p>
<p>Well, VC++ 2012 shipped four weeks ago.</p>
<p>What’s happened since then?</p>
<p>&#160;</p>
<p><strong><font size="4">3. </font></strong>On the same day VS2012 shipped, four weeks ago, we also <a href="http://herbsutter.com/2012/09/12/vc-2012-desktop-expres-free/">announced and released Visual Studio 2012 <strong>Desktop Express</strong></a> – a free Visual Studio version for writing traditional Windows applications.</p>
<p>&#160;</p>
<p><a href="http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-65-69/7725.xptarget.png"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/10/image.png?w=364&#038;h=135" width="364" height="135" /></a><strong><font size="4">2. </font></strong>Today, we are pleased to share a <a href="http://blogs.msdn.com/b/vcblog/archive/2012/10/08/10357555.aspx">“community tech preview” (CTP) of <strong>Windows XP targeting </strong>in Visual C++ 2012</a>, being delivered as part of Visual Studio 2012 Update 1 CTP 3. You can download the preview <strong><a href="http://aka.ms/ms3oxw">here</a></strong>. See the announcement page for details, known issues, and full release information.</p>
<p>&#160;</p>
<p><strong><font size="4">1. </font></strong>Stay tuned…</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1627&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/10/09/ctp-of-windows-xp-targeting-with-c-in-visual-studio-2012/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/10/image.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Poll: What features would you like to see added soonest in your favorite C++ compiler?</title>
		<link>http://herbsutter.com/2012/10/03/poll-what-features-would-you-like-to-see-added-soonest-in-your-favorite-c-compiler/</link>
		<comments>http://herbsutter.com/2012/10/03/poll-what-features-would-you-like-to-see-added-soonest-in-your-favorite-c-compiler/#comments</comments>
		<pubDate>Wed, 03 Oct 2012 16:01:58 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1619</guid>
		<description><![CDATA[I just got back from teaching a class, and I&#8217;m always amazed at the breadth and diversity of C++ developers. As Bjarne Stroustrup famously says: &#8220;No one knows &#8216;what most C++ developers do.&#8217;&#8221; In particular, I&#8217;m surprised at how strongly some people feel about certain features, such as refactoring or safety or raw performance or [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1619&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I just got back from teaching a class, and I&#8217;m always amazed at the breadth and diversity of C++ developers. As Bjarne Stroustrup famously says: &#8220;No one knows &#8216;what most C++ developers do.&#8217;&#8221;</p>
<p>In particular, I&#8217;m surprised at how strongly some people feel about certain features, such as refactoring or safety or raw performance or exhaustive conformance, that don&#8217;t matter much at all to other people, and it made me wonder how a cross-section of the C++ developer community might prioritize them if I ran a poll.</p>
<p>So let me pose a question: Whether you use gcc or Clang or VC++ or Intel C++ or any other compiler, <em><strong>if you could only pick five of the following</strong></em> for your compiler to implement in its very next release, which would they be? Note that this is intended to be purely an &#8220;urgency&#8221; or ordering exercise, not an &#8220;importance&#8221; or eventually-will/won&#8217;t-do exercise &#8212; assume that your compiler vendor would eventually add everything possible from the list in their next few releases, and ask yourself only what would you just love to have in your hands <em><strong>the very soonest, right away</strong></em>?</p>
<p>(This is not intended to be a complete list, by the way, just picking some things I&#8217;ve again recently heard people mention, to validate how broadly interesting they really are.)</p>
<p>Thanks in advance for your participation. I&#8217;m really curious to see the results.</p>
<p><em><span style="color:#339966;">[Updated to add: Several people have asked to change the poll to add an option for "faster build times". I won't change the poll while in progress which would skew results, but for now if you want to vote for "faster builds" please post it as a comment and I'll manually add those comments up since that seems to be a popular request.]</span></em></p>
<a name="pd_a_6580284"></a>
<div class="PDS_Poll" id="PDI_container6580284" data-settings="{&quot;url&quot;:&quot;http:\/\/static.polldaddy.com\/p\/6580284.js&quot;}" style="display:inline-block;"></div>
<div id="PD_superContainer"></div>
<noscript><a href="http://polldaddy.com/poll/6580284">Take Our Poll</a></noscript>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1619&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/10/03/poll-what-features-would-you-like-to-see-added-soonest-in-your-favorite-c-compiler/feed/</wfw:commentRss>
		<slash:comments>92</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Casablanca: C++ on Azure</title>
		<link>http://herbsutter.com/2012/09/19/casablanca-c-on-azure/</link>
		<comments>http://herbsutter.com/2012/09/19/casablanca-c-on-azure/#comments</comments>
		<pubDate>Wed, 19 Sep 2012 22:05:06 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1617</guid>
		<description><![CDATA[I’ve blogged about Casablanca before. Here’s a related talk from TechEd Australia: Casablanca is a Microsoft incubation effort to support cloud-based client-server communication in native code using a modern asynchronous C++ API design. Think of it as Node.js, but using C++ – from simple services, to JSON and REST, to Azure storage and deployment, and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1617&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Events/TechEd/Australia/2012/AZR331"><img title="azr331" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="azr331" align="right" src="http://herbsutter.files.wordpress.com/2012/09/azr331.png?w=244&#038;h=140" width="244" height="140" /></a>I’ve blogged about Casablanca <a href="http://herbsutter.com/2012/04/30/c-libraries-casablanca/">before</a>. Here’s a related talk from TechEd Australia:</p>
<blockquote><p>Casablanca is a Microsoft incubation effort to support cloud-based client-server communication in native code using a modern asynchronous C++ API design. Think of it as Node.js, but using C++ – from simple services, to JSON and REST, to Azure storage and deployment, and more.</p>
<p>Casablanca gives you the power to use existing native C++ libraries and code to do awesome things on the cloud server. In this talk from TechEd Australia, <a href="http://channel9.msdn.com/Events/TechEd/Australia/2012/AZR331">John Azariah and Mahesh Krishnan show how it’s done</a>.</p>
</blockquote>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/cloud/'>Cloud</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1617&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/09/19/casablanca-c-on-azure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/09/azr331.png" medium="image">
			<media:title type="html">azr331</media:title>
		</media:content>
	</item>
		<item>
		<title>C&amp;B 2012 panel posted: Ask Us Anything!</title>
		<link>http://herbsutter.com/2012/09/18/cb-2012-panel-posted-ask-us-anything/</link>
		<comments>http://herbsutter.com/2012/09/18/cb-2012-panel-posted-ask-us-anything/#comments</comments>
		<pubDate>Tue, 18 Sep 2012 20:53:01 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1613</guid>
		<description><![CDATA[The second panel from C++ and Beyond 2012 is now available on Channel 9: Alexandrescu, Meyers and Sutter &#8211; Ask Us Anything Here is the “Ask Us Anything” panel from C++ and Beyond 2012. Andrei Alexandrescu, Scott Meyers and Herb Sutter take questions from attendees. As expected, great questions and answers… Table of contents (click [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1613&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything"><img title="cnb2012-panel" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;margin:0 0 10px 10px;border-left:0;display:inline;padding-right:0;" border="0" alt="cnb2012-panel" align="right" src="http://herbsutter.files.wordpress.com/2012/09/cnb2012-panel.png?w=244&#038;h=165" width="244" height="165" /></a>The second panel from <em>C++ and Beyond 2012</em> is now available on Channel 9:</p>
<blockquote><h5><a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything">Alexandrescu, Meyers and Sutter &#8211; Ask Us Anything</a></h5>
<p>Here is the “Ask Us Anything” panel from <em>C++ and Beyond 2012</em>.</p>
<p>Andrei Alexandrescu, Scott Meyers and Herb Sutter take questions from attendees. As expected, great questions and answers…</p>
<p><strong>Table of contents</strong> (click the time codes ([xx:xx]) to hear the answers&#8230;):</p>
<ul>
<li>message passing primitives in future versions of the standard&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=00m00s">[00:00]</a></li>
<li>standardized unit testing framework&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=2m55s">[02:55]</a></li>
<li>std::async&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=4m30s">[04:30]</a></li>
<li>standard modules proposal&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=8m14s">[08:14]</a></li>
<li>keyword additions and the standard library&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=9m35s">[09:35]</a></li>
<li>problems (and solutions) with exceptions&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=12m50s">[12:50]</a></li>
<li>future of concepts&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=22m34s">[22:34]</a></li>
<li>std::thread and thread interruption&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=23m03s">[23:03]</a></li>
<li>when to use the auto keyword (and when not to&#8230;)&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=25m03s">[25:03]</a></li>
<li>more on auto (benefits of reduncancy, type conversion issues with bool to int?)&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=29m31s">[29:31]</a></li>
<li>const and multithreaded programming, in C++11 const means thread safe, too&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=35m00s">[35:00]</a></li>
<li>yet more on auto (impact on rampant use and code readability/comprehension)&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=42m42s">[42:42]</a></li>
<li>compiler type deduction information (compiler switch that prints out auto deduced type information)&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=50m18s">[50:18]</a></li>
<li>printing out code for review that replaces auto with the actual type&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=53m30s">[53:30]</a></li>
<li>auto and dynamic memory allocation&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=54m59s">[54:59]</a></li>
<li>useful, broadly-used concurrency libraries&#8230; <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Scott-Andrei-and-Herb-Ask-Us-Anything#time=57m00s">[57:00]</a></li>
</ul>
</blockquote>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1613&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/09/18/cb-2012-panel-posted-ask-us-anything/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/09/cnb2012-panel.png" medium="image">
			<media:title type="html">cnb2012-panel</media:title>
		</media:content>
	</item>
		<item>
		<title>VC++ 2012 Desktop Express (Free)</title>
		<link>http://herbsutter.com/2012/09/12/vc-2012-desktop-expres-free/</link>
		<comments>http://herbsutter.com/2012/09/12/vc-2012-desktop-expres-free/#comments</comments>
		<pubDate>Wed, 12 Sep 2012 19:00:39 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1607</guid>
		<description><![CDATA[Today Microsoft released another free Express version of Visual C++ 2012. In addition to the free Express Visual C++ compiler for building tablet applications, Visual Studio Express 2012 for Windows Desktop directly supports traditional Windows and command-line applications in C++. This a great free C++ compiler on Windows for everything from hobby development to using [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1607&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h5></h5>
<p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=34673"><img style="float:right;margin:0 0 10px 10px;display:inline;" src="http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-29-92-metablogapi/6013.clip_5F00_image0061_5F00_65C1E1B0.jpg" alt="" width="450" height="225" align="right" /></a>Today Microsoft released another free Express version of Visual C++ 2012. In addition to the free Express Visual C++ compiler for building tablet applications, <strong><a href="http://www.microsoft.com/en-us/download/details.aspx?id=34673">Visual Studio Express 2012 for Windows Desktop</a></strong> directly supports traditional Windows and command-line applications in C++.</p>
<p>This a great free C++ compiler on Windows for everything from hobby development to using and contributing to open source projects. Besides additional C++11 standards conformance with range-for, override and final on the language side (with more to come in the coming months; watch this space) and a complete C++11 standard library implementation, the free compiler also includes unit testing framework for C++, code analysis for C++ (try /analyze today if you haven’t already, <a href="http://www.altdevblogaday.com/2011/12/24/static-code-analysis/">as John Carmack says so well</a>), C++ AMP for GPGPU programming, and much more.</p>
<p><a href="http://blogs.msdn.com/b/visualstudio/archive/2012/09/12/visual-studio-express-2012-for-windows-desktop-is-here.aspx">See also the longer announcement here.</a></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1607&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/09/12/vc-2012-desktop-expres-free/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-29-92-metablogapi/6013.clip_5F00_image0061_5F00_65C1E1B0.jpg" medium="image" />
	</item>
		<item>
		<title>Reader Q&amp;A: How to write a CAS loop using std::atomics</title>
		<link>http://herbsutter.com/2012/08/31/reader-qa-how-to-write-a-cas-loop-using-stdatomics/</link>
		<comments>http://herbsutter.com/2012/08/31/reader-qa-how-to-write-a-cas-loop-using-stdatomics/#comments</comments>
		<pubDate>Sat, 01 Sep 2012 00:43:58 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Concurrency]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1599</guid>
		<description><![CDATA[The following is not intended to be a complete treatise on atomics, but just an answer to a specific question. A colleague asked: How should one write the following “conditional interlocked” function in the new C++ atomic&#60;&#62; style? // if (*plValue &#62;= 0) *plValue += lAdd ; return the original value LONG MpInterlockedAddNonNegative(__inout LONG volatile* [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1599&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The following is not intended to be a complete treatise on atomics, but just an answer to a specific question.</p>
<p>A colleague asked:</p>
<blockquote><p>How should one write the following “conditional interlocked” function in the new C++ atomic&lt;&gt; style?</p>
<pre class="brush: cpp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">// if (*plValue &gt;= 0) *plValue += lAdd  ; return the original value

LONG MpInterlockedAddNonNegative(__inout LONG volatile* plValue,  __in  LONG const  lAdd) 
{ 
    LONG lValue = 0; 
    for (;;)  {

        lValue = *plValue; // volatile plValue suppress compile optimizations in which</pre>
<p>&#160;</p>
<pre class="brush: cpp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">                           // lValue is optimized out hence MT correctness is broken

        if (lValue &lt; 0)   break;

        if (lValue == InterlockedCompareExchange(plValue, lValue + lAdd, lValue)) { 
            break; 
        } 
    }

    return lValue; 
}</pre>
</blockquote>
<p>Note: ISO C/C++ volatile is not for inter-thread communication,[*] but this is legacy code that predates std::atomics and was using a combination of platform-specific volatile semantics and Windows InterlockedXxx APIs.</p>
<p>The answer is to use a CAS loop (see code at top), which for std::atomics is spelled compare_exchange:</p>
<ul>
<li>Use compare_exchange_weak by default when looping on this which generally naturally tolerates spurious failures. </li>
<li>Use compare_exchange_strong for single tests when you generally don’t want spurious failures. </li>
<li>Usage note: In the code at top we save an explicit reload from ‘a’ in the loop because compare_exchange helpfully (or “helpfully” – this took me a while to discover and remember) stores the actual value in the ‘expected’ value slot on failure. This actually makes loops simpler, though some of us are still have different feelings on different days about whether this subtlety was a good idea… anyway, it’s in the standard. </li>
</ul>
<p>For the std::atomic version, roughly (compiling in my head), and generalizing to any numeric type just because I’m in the habit, and renaming for symmetry with atomic&lt;T&gt;::fetch_add(), I think this is what you want:</p>
<pre class="brush: cpp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">template&lt;typename T&gt;
T fetch_add_if_nonnegative( std::atomic&lt;T&gt;&amp; a,  T val ) {
    T old = a;
    while( old &gt;= 0 &amp;&amp; !a.compare_exchange_weak( old, old+val ) )
        { }
    return old;
}</pre>
<p>Because the only test in your loop was to break on negative values, it naturally migrated into the loop condition. If you want to do more work, then follow the general pattern which is the following (pasting from the standard, 29.6.5/23 – and note that the explicit “.load()” is unnecessary but some people including the author of this clause of the standard prefer to be pedantically explicit :) ):</p>
<blockquote>
<p>[ <em>Example: </em>the expected use of the compare-and-exchange operations is as follows.</p>
<p>The compare-and-exchange operations will update expected when another iteration of the loop is needed.</p>
<p>expected = current.load();</p>
<p>do {</p>
<p>desired = function(expected);</p>
<p>} while (!current.compare_exchange_weak(expected, desired));</p>
<p><em>—end example </em>]</p>
</blockquote>
<p>So the direct implementation of your function in the general pattern would be:</p>
<pre class="brush: cpp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">T old = a; 
do { 
    if( old &lt; 0 ) break; 
} while(!a.compare_exchange_weak( old, old+val ) )</pre>
<p>
  <br />but since that easily moves into the loop test I just did this instead in the code at top:</p>
<p></p>
<pre class="brush: cpp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">T old = a; 
while( old &gt;= 0 &amp;&amp; !a.compare_exchange_weak( old, old+val ) ) 
    { }</pre>
<p>and hoping that no one will discover and point out that I’ve somehow written a subtle bug by trying to make the code cuter just before leaving for a holiday weekend.</p>
<p>&#160;</p>
<p>[*] Here’s the difference between <strong>ISO C/C++ volatile vs. std::atomic&lt;T&gt;/atomic_T:</strong> ISO C/C++ volatile is intended to be used only for things like hardware access and setjmp/longjmp safety, to express that the variable is in storage that is not guaranteed to follow the C++11 memory model (e.g., the compiler can’t make any assumptions about it). It has nothing to do with inter-thread communication – the proper tool for that is std::atomic&lt;T&gt; which for C compatibility can also be spelled atomic_T (note that in Java and C# this is called volatile which adds to the confusion). For more, see my article <a href="http://herbsutter.com/2009/01/12/effective-concurrency-volatile-vs-volatile/">“volatile vs. volatile”</a> and Hans Boehm’s ISO C++ paper <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html">“Should volatile Acquire Atomicity and Thread Visibility Semantics?”</a>.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1599&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/08/31/reader-qa-how-to-write-a-cas-loop-using-stdatomics/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>C&amp;B Panel: Alexandrescu, Meyers, Sutter on Static If, C++11, and Metaprogramming</title>
		<link>http://herbsutter.com/2012/08/21/cb-panel/</link>
		<comments>http://herbsutter.com/2012/08/21/cb-panel/#comments</comments>
		<pubDate>Tue, 21 Aug 2012 15:10:26 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">http://herbsutter.com/?p=1596</guid>
		<description><![CDATA[The first panel from C++ and Beyond 2012 is now available on Channel 9: On Static If, C++11 in 2012, Modern Libraries, and Metaprogramming Andrei Alexandrescu, Scott Meyers, Herb Sutter Channel 9 was invited to this year&#8217;s C++ and Beyond to film some sessions (that will appear on C9 over the coming months!)&#8230; At the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1596&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://channel9.msdn.com/Shows/Going+Deep/Alexandrescu-Meyers-Sutter-On-Static-If-C11-in-2012-Modern-Libraries-and-Metaprogramming"><img class="alignright size-full wp-image-1597" title="C&amp;B 2012 Panel" src="http://herbsutter.files.wordpress.com/2012/08/cnb2012-panel.png?w=500" alt=""   /></a>The first panel from C++ and Beyond 2012 is now available on Channel 9:</p>
<blockquote><p><a href="http://s151836.gridserver.com/?URL=http%3A%2F%2Fchannel9.msdn.com%2FShows%2FGoing%2BDeep%2FAlexandrescu-Meyers-Sutter-On-Static-If-C11-in-2012-Modern-Libraries-and-Metaprogramming">On Static If, C++11 in 2012, Modern Libraries, and Metaprogramming</a></p>
<h4>Andrei Alexandrescu, Scott Meyers, Herb Sutter</h4>
<p>Channel 9 was invited to this year&#8217;s <a href="http://s151836.gridserver.com/?URL=http%3A%2F%2Fcppandbeyond.com%2F">C++ and Beyond</a> to film some sessions (that will appear on C9 over the coming months!)&#8230;</p>
<p>At the end of day 2, Andrei, Herb and Scott graciously agreed to spend some time discussing various modern C++ topics and, even better, <a href="http://s151836.gridserver.com/?URL=http%3A%2F%2Fchannel9.msdn.com%2FForums%2FTechOff%2FAndrei-Herb-and-Scott-Got-C11-Questions">answering questions from the community</a>. In fact, the questions from Niners (and <a href="http://s151836.gridserver.com/?URL=http%3A%2F%2Fwww.reddit.com%2Fr%2Fcpp%2Fcomments%2Fxknfr%2Fandrei_herb_and_scott_got_c11_questions%2F">a conversation on reddit/r/cpp</a>) drove the conversation.</p>
<p>Here&#8217;s what happened&#8230;</p>
<p><a href="http://s151836.gridserver.com/?URL=http%3A%2F%2Fchannel9.msdn.com%2FShows%2FGoing%2BDeep%2FAlexandrescu-Meyers-Sutter-On-Static-If-C11-in-2012-Modern-Libraries-and-Metaprogramming">[more]</a></p></blockquote>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1596&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/08/21/cb-panel/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/08/cnb2012-panel.png" medium="image">
			<media:title type="html">C&#38;B 2012 Panel</media:title>
		</media:content>
	</item>
		<item>
		<title>&#8220;Strong&#8221; and &#8220;weak&#8221; hardware memory models</title>
		<link>http://herbsutter.com/2012/08/02/strong-and-weak-hardware-memory-models/</link>
		<comments>http://herbsutter.com/2012/08/02/strong-and-weak-hardware-memory-models/#comments</comments>
		<pubDate>Thu, 02 Aug 2012 11:26:37 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C# / .NET]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1590</guid>
		<description><![CDATA[In Welcome to the Jungle, I predicted that “weak” hardware memory models will disappear. This is true, and it’s happening before our eyes: x86 has always been considered a “strong” hardware memory model that supports sequentially consistent atomics efficiently. The other major architecture, ARM, recently announced that they are now adding strong memory ordering in [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1590&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://herbsutter.com/welcome-to-the-jungle/">Welcome to the Jungle</a>, I predicted that “weak” hardware memory models will disappear. This is true, and it’s happening before our eyes:</p>
<ul>
<li>x86 has always been considered a “strong” hardware memory model that supports sequentially consistent atomics efficiently.</li>
<li>The other major architecture, ARM, recently announced that they are now adding strong memory ordering in ARMv8 with the new sequentially consistent <em>ldra </em>and <em>strl </em>instructions, as I predicted they would. (Actually, Hans Boehm and I influenced ARM in this direction, so it was an ever-so-slightly disingenuous prediction&#8230;)</li>
</ul>
<p>However, at least two people have been confused by what I meant by “weak” hardware memory models, so let me clarify what “weak” means – it means something different for hardware memory models and software memory models, so perhaps those aren’t the clearest terms to use.</p>
<p>By &#8220;weak <strong><em>(hardware)</em></strong> memory model&#8221; CPUs I mean specifically ones that do not natively support efficient sequentially consistent (SC) atomics, because on the <strong><em>software</em></strong> side programming languages have converged on &#8220;sequential consistency for data-race-free programs&#8221; (SC-DRF, roughly aka DRF0 or RCsc) as the default (C11, C++11) or only (Java 5+) supported software memory model for software. POWER and ARMv7 notoriously do not support SC atomics efficiently.</p>
<p>Hardware that supports only hardware memory models weaker than SC-DRF, <em>meaning that they do not support SC-DRF efficiently</em>, are permanently disadvantaged and will either become stronger or atrophy. As I mentioned specifically in the article, the two main current hardware architectures with what I called &#8220;weak&#8221; memory models were current ARM (ARMv7) and POWER:</p>
<ul>
<li>ARM recently announced ARMv8 which, as I predicted, is upgrading to SC acquire/release by adding new SC acquire/release instructions ldra and strl that are mandatory in both 32-bit and 64-bit mode. In fact, this is something of an industry first &#8212; ARMv8 is the first major CPU architecture to support SC acquire/release instructions directly like this. (Note: That’s for CPUs, but the roadmap for ARM GPUs is similar. ARM GPUs currently have a stronger memory model, namely fully SC; ARM has announced their GPU future roadmap has the GPUs fully coherent with the CPUs, and will likely add “SC load acquire” and “SC store release” to GPUs as well.)</li>
<li>It remains to be seen whether POWER will adapt similarly, or die out.</li>
</ul>
<p>Note that I&#8217;ve seen some people call x86 &#8220;weak&#8221;, but x86 has always been the poster child for a <strong><em>strong (hardware) </em></strong>memory model in all of our <strong><em>software</em></strong> memory model discussions for Java, C, and C++ during the 2000s. Therefore perhaps &#8220;weak&#8221; and &#8220;strong&#8221; are not useful terms if they mean different things to some people, and I&#8217;ve updated the WttJ text to make this clearer.</p>
<p>I will be discussing this in detail in my <a href="http://herbsutter.com/2012/06/29/cb-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/">atomic&lt;&gt; Weapons</a> talk at C&amp;B next week, which I hope to make freely available online in the near future (as I do most of my talks). I’ll post a link on this blog when I can make it available online.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c-net/'>C# / .NET</a>, <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/hardware/'>Hardware</a>, <a href='http://herbsutter.com/category/java/'>Java</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1590&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/08/02/strong-and-weak-hardware-memory-models/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Late-Breaking C&amp;B Session: A Special Announcement</title>
		<link>http://herbsutter.com/2012/07/30/late-breaking-cb-session-a-special-announcement/</link>
		<comments>http://herbsutter.com/2012/07/30/late-breaking-cb-session-a-special-announcement/#comments</comments>
		<pubDate>Mon, 30 Jul 2012 15:11:46 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1587</guid>
		<description><![CDATA[At the end of the Monday afternoon session, I will be making a special announcement related to Standard C++ on all platforms. Be there to hear the details, and to receive an extra perk that’s being reserved for C&#38;B 2012 attendees only. Note: We sometimes record sessions and make them freely available online via Channel [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1587&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://herbsutter.files.wordpress.com/2012/07/image_thumb.png"><img title="image_thumb" style="border-top:0;border-right:0;background-image:none;border-bottom:0;float:right;padding-top:0;padding-left:0;border-left:0;display:inline;padding-right:0;" border="0" alt="image_thumb" align="right" src="http://herbsutter.files.wordpress.com/2012/07/image_thumb_thumb.png?w=244&#038;h=244" width="244" height="244" /></a></p>
<p>At the end of the Monday afternoon session, I will be making a special announcement related to Standard C++ on all platforms. Be there to hear the details, and to receive an extra perk that’s being reserved for <a href="http://cppandbeyond.com/">C&amp;B 2012</a> attendees only.</p>
<ul>
<li>Note: We sometimes record sessions and make them freely available online via Channel 9, and we intend to do that again this year for some selected sessions. <strong>However, this session is for C&amp;B attendees only and will not be recorded.</strong></li>
</ul>
<p><a href="http://cppandbeyond2012.eventbrite.com/">Registration is open until Wednesday</a> and the event is pretty full but a few spaces are still available. I’m looking forward to seeing many of you there for a top-notch C++ conference full of fresh new current material – I’ve seen Andrei’s and Scott’s talk slides too, and I think this C&amp;B is going to be the best one yet.</p>
<p>You’ll leave exhausted, but with a full brain and quite likely a big silly grin as you think about all the ways to use the material right away on your current project back home.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1587&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/07/30/late-breaking-cb-session-a-special-announcement/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/07/image_thumb_thumb.png" medium="image">
			<media:title type="html">image_thumb</media:title>
		</media:content>
	</item>
		<item>
		<title>C&amp;B Session: atomic&lt;&gt; Weapons &#8211; The C++11 Memory Model and Modern Hardware</title>
		<link>http://herbsutter.com/2012/06/29/cb-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/</link>
		<comments>http://herbsutter.com/2012/06/29/cb-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/#comments</comments>
		<pubDate>Fri, 29 Jun 2012 19:41:39 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1578</guid>
		<description><![CDATA[Here’s another deep session for C&#38;B 2012 on August 5-8 – if you haven’t registered yet, register soon. We got a bigger venue this time, but as I write this the event is currently almost 75% full with five weeks to go. I know, I’ve already posted three sessions and a panel. But there’s just [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1578&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://cppandbeyond.com/2012/06/29/new-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/"><img title="image" style="background-image:none;float:right;padding-top:0;padding-left:0;margin:10px 0 10px 10px;display:inline;padding-right:0;border-width:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/06/image2.png?w=241&#038;h=241" width="241" height="241" /></a>Here’s another deep session for C&amp;B 2012 on August 5-8 – if you haven’t registered yet, <a href="http://cppandbeyond2012.eventbrite.com/">register soon</a>. We got a bigger venue this time, but as I write this the event is currently almost 75% full with five weeks to go.</p>
<p>I know, I’ve already posted <a href="http://cppandbeyond.com/2012/03/26/session-topic-you-dont-know-and/">three</a> <a href="http://cppandbeyond.com/2012/05/28/two-sessions-c-concurrency-and-parallelism-2012-state-of-the-art-and-standard/">sessions</a> and a <a href="http://cppandbeyond.com/2012/04/30/panel-modern-c-clean-safe-and-faster-than-ever/">panel</a>. But there’s just so much about C++11 to cover, so here’s a fourth brand-new session I’ll do at C&amp;B 2012 that goes deeper on its topic than I’ve ever been willing to go before.</p>
<blockquote><h3><a href="http://cppandbeyond.com/2012/06/29/new-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/"><font>atomic&lt;&gt; Weapons: The C++11 Memory Model and Modern Hardware</font></a></h3>
</blockquote>
<p>This session in one word: <i><strong>Deep.</strong></i> </p>
<p>It’s a session that includes topics I’ve publicly said for years is Stuff You Shouldn’t Need To Know and I Just Won’t Teach, but it’s becoming achingly clear that people do need to know about it. Achingly, heartbreakingly clear, because some hardware incents you to pull out the big guns to achieve top performance, and C++ programmers just are so addicted to full performance that they’ll reach for the big red levers with the flashing warning lights. Since we can’t keep people from pulling the big red levers, we’d better document the A to Z of what the levers actually do, so that people don’t <a href="http://en.wikipedia.org/wiki/Scram">SCRAM</a> unless they really, really, really meant to. </p>
<p>This session covers: </p>
<ul>
<li><strong>The facts: </strong>The C++11 memory model and what it requires you to do to make sure your code is correct and stays correct. We’ll include clear answers to several FAQs: “how do the compiler and hardware cooperate to remember how to respect these rules?”, “what is a race condition?”, and the ageless one-hand-clapping question “how is a race condition like a debugger?” </li>
<li><strong>The tools:</strong> The deep interrelationships and fundamental tradeoffs among mutexes, atomics, and fences/barriers. I’ll try to convince you why standalone memory barriers are bad, and why barriers should always be associated with a specific load or store. </li>
<li><strong>The unspeakables: </strong>I’ll grudgingly and reluctantly talk about the Thing I Said I’d Never Teach That Programmers Should Never Need To Now: relaxed atomics. Don’t use them! If you can avoid it. But here’s what you need to know, even though it would be nice if you didn’t need to know it. </li>
<li><strong>The rapidly-changing hardware reality: </strong>How locks and atomics map to hardware instructions on ARM and x86/x64, and throw in POWER and Itanium for good measure – and I’ll cover how and why the answers are actually different last year and this year, and how they will likely be different again a few years from now. We’ll cover how the latest CPU and GPU hardware memory models are rapidly evolving, and how this directly affects C++ programmers. </li>
<li><strong>Coda: Volatile and “compiler-only” memory barriers.</strong> It’s important to understand exactly what atomic and volatile are and aren’t for. I’ll show both why they’re both utterly unrelated (they have exactly zero overlapping uses, really) and yet are fundamentally related when viewed from the perspective of talking about the memory model. Also, people keep seeing and asking about “compiler-only” memory barriers and when to use them – they do have a valid-though-rare use, but it’s not the use that most people are trying to use them for, so beware! </li>
</ul>
<p>For me, this is going to be the deepest and most fun C&amp;B yet. At previous C&amp;Bs I’ve spoken about not only code, but also meta topics like design and C++’s role in the marketplace. This time it looks like all my talks will be back to Just Code. Fun times!</p>
<p>Here a snapshot of the <a href="http://cppandbeyond.com/cb2012-schedule/">list of C&amp;B 2012 sessions</a> so far:</p>
<blockquote><p><a href="http://cppandbeyond.com/2012/03/13/session-topic-universal-references-in-c11/">Universal References in C++11</a> (Scott)       <br /><a href="http://cppandbeyond.com/2012/03/26/session-topic-you-dont-know-and/">You Don’t Know [keyword] and [keyword]</a> (Herb)       <br /><a href="http://cppandbeyond.com/2012/04/02/panel-session-topic-convincing-your-colleagues/">Convincing Your Colleagues</a> (Panel)       <br /><a href="http://cppandbeyond.com/2012/04/16/session-topic-initial-thoughts-on-effective-c11/">Initial Thoughts on Effective C++11</a> (Scott)       <br /><a href="http://cppandbeyond.com/2012/04/30/panel-modern-c-clean-safe-and-faster-than-ever/">Modern C++ = Clean, Safe, and Faster Than Ever</a> (Panel)       <br /><a href="http://cppandbeyond.com/2012/04/30/session-topics-error-resilience-in-c11/">Error Resilience in C++11</a> (Andrei)       <br /><a href="http://cppandbeyond.com/2012/05/28/two-sessions-c-concurrency-and-parallelism-2012-state-of-the-art-and-standard/">C++ Concurrency – 2012 State of the Art (and Standard)</a> (Herb)       <br /><a href="http://cppandbeyond.com/2012/05/28/two-sessions-c-concurrency-and-parallelism-2012-state-of-the-art-and-standard/">C++ Parallelism – 2012 State of the Art (and Standard)</a> (Herb)       <br /><a href="http://cppandbeyond.com/2012/06/21/session-topic-secrets-of-the-c11-threading-api/">Secrets of the C++11 Threading API</a> (Scott)       <br /><a href="http://cppandbeyond.com/2012/06/29/new-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/">atomic&lt;&gt; Weapons: The C++11 Memory Model and Modern Hardware</a> (Herb)</p>
</blockquote>
<p>It’ll be a blast. I hope to see many of you there. <a href="http://cppandbeyond2012.eventbrite.com/">Register soon.</a></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/hardware/'>Hardware</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1578&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/29/cb-session-atomic-weapons-the-c11-memory-model-and-modern-hardware/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/06/image2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Reader Q&amp;A: Why don&#8217;t modern smart pointers implicitly convert to *?</title>
		<link>http://herbsutter.com/2012/06/21/reader-qa-why-dont-modern-smart-pointers-implicitly-convert-to/</link>
		<comments>http://herbsutter.com/2012/06/21/reader-qa-why-dont-modern-smart-pointers-implicitly-convert-to/#comments</comments>
		<pubDate>Thu, 21 Jun 2012 20:58:35 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Reader Q&A]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1574</guid>
		<description><![CDATA[Today a reader asked a common question: Why doesn&#8217;t unique_ptr (and the ilk) appear to have an operator overload somewhat as follows: operator T*() { return get(); }; The reason I ask is because we have reams of old code wanting raw pointers (as function parms), and I would like to replace the outer layers [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1574&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Today a reader asked a common question:</p>
<blockquote><p>Why doesn&#8217;t <em>unique_ptr</em> (and the ilk) appear to have an operator overload somewhat as follows:</p>
<p><em>operator T*() { return get(); };</em></p>
<p>The reason I ask is because we have reams of old code wanting raw pointers (as function parms), and I would like to replace the outer layers of the code which deal with the allocation and deallocation with <em>unique_ptr</em>s without having to either ripple <em>unique_ptr</em>s through the entire system or explicitly call <em>.get() </em>every time the <em>unique_ptr </em>is a parm to a function which wants a raw pointer.</p>
<p>What my programmers are doing is creating a <em>unique_ptr</em> and immediately using <em>get()</em> to put it into a local raw pointer which is used from then on. Somehow that doesn&#8217;t feel right, but I don&#8217;t know what would be the best alternative.</p>
</blockquote>
<p>In the olden days, smart pointers often did provide the convenience of implicit conversion to *. It was by using those smart pointers that we learned it caused more problems than it solves, and that requiring people to write <em>.get()</em> was actually not a big deal.</p>
<p>For an example of the problems of implicit conversions, consider:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8cba2f5e-981e-475e-9082-42b8b86c529f" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<pre style="white-space:normal;">
<pre class="brush: cpp; gutter: false; pad-line-numbers: true; title: ; notranslate">
unique_ptr p( new widget );
...
use( p + 42 ); // error (maybe he meant "*p + 42"?)
    // but if implicit conversion to * were allowed, would silently compile -- urk
...
delete p; // error
    // but if implicit conversion to * were allowed, would silently compile -- double urk
</pre>
</div>
<p>For more, see also Andrei’s <em>Modern C++ Design</em> <a href="http://www.informit.com/articles/article.aspx?p=31529&amp;seqNum=7">section 7.7, “Implicit Conversion to Raw Pointer Types.”</a></p>
<p>However, this really isn’t as bad as most people fear for several reasons, including but not limited to:</p>
<ul>
<li>The large majority of uses of the smart pointer, such as calling member functions on the object (e.g., <em>p-&gt;foo()</em>)&#160; just work naturally and effortlessly because we do have <em>operator-&gt;</em>.</li>
<li>You rarely if ever need to say <em>unique_ptr</em> on a local variable, because C++11’s <em>auto </em>is your friend – and “rarely” becomes “never” if you use <em>make_unique</em> which is described <a href="http://herbsutter.com/gotw/_102/">here</a> and should become standard in the future.</li>
<li>Parameters (which you mention) themselves should almost never be smart pointers, but should be normal pointers and references. So if you’re managing an object’s lifetime by smart pointer, you do write <em>.get()</em> – but only once at the top of each call tree. More on this in the current <a href="http://herbsutter.com/2012/06/05/gotw-105-smart-pointers-part-3-difficulty-710/">GotW #105</a> – solution coming soon, watch this space.</li>
</ul>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/reader-qa/'>Reader Q&amp;A</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1574&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/21/reader-qa-why-dont-modern-smart-pointers-implicitly-convert-to/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Talk Video: Welcome to the Jungle (60 min version + Q&amp;A)</title>
		<link>http://herbsutter.com/2012/06/21/talk-video-welcome-to-the-jungle-60-min-version-qa/</link>
		<comments>http://herbsutter.com/2012/06/21/talk-video-welcome-to-the-jungle-60-min-version-qa/#comments</comments>
		<pubDate>Thu, 21 Jun 2012 20:40:10 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Talks & Events]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1572</guid>
		<description><![CDATA[While visiting Facebook earlier this month, I gave a shorter version of my “Welcome to the Jungle” talk, based on the eponymous WttJ article. They made a nice recording and it’s now available online here: Facebook Engineering Title: Herb Sutter: Welcome to the Jungle In the twilight of Moore&#8217;s Law, the transitions to multicore processors, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1572&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="https://www.facebook.com/photo.php?v=10151029515183109"><img title="image" style="background-image:none;float:right;padding-top:0;padding-left:0;margin:10px 0 10px 10px;display:inline;padding-right:0;border-width:0;" border="0" alt="image" align="right" src="http://herbsutter.files.wordpress.com/2012/06/image.png?w=324&#038;h=174" width="324" height="174" /></a>While visiting Facebook earlier this month, I gave a shorter version of my “Welcome to the Jungle” talk, based on the <a href="http://herbsutter.com/welcome-to-the-jungle/">eponymous WttJ article</a>. They made a nice recording and it’s now available online here:</p>
<blockquote><p><strong>Facebook Engineering</strong></p>
<p><a href="https://www.facebook.com/photo.php?v=10151029515183109"><strong>Title: Herb Sutter: Welcome to the Jungle</strong></a></p>
<p>In the twilight of Moore&#8217;s Law, the transitions to multicore processors, GPU computing, and HaaS cloud computing are not separate trends, but aspects of a single trend—mainstream computers from desktops to &#8216;smartphones&#8217; are being permanently transformed into heterogeneous supercomputer clusters. Henceforth, a single compute-intensive application will need to harness different kinds of cores, in immense numbers, to get its job done. &#8212; The free lunch is over. Now welcome to the hardware jungle.</p>
</blockquote>
<p>The <a href="https://developers.facebook.com/attachment/Welcome_to_the_Jungle_-_FB-pdf/">slides are available here</a>. (There doesn’t seem to be a link to the slides on the page itself as I write this.)</p>
<p>For those interested in a longer version, in April I gave a 105-minute + Q&amp;A version of this talk in Kansas City at Perceptive, also <a href="http://herbsutter.com/2012/04/23/talk-video-welcome-to-the-jungle/">available online where I posted before</a>.</p>
<h3>A word about “cluster in a box”</h3>
<p>I should have remembered that describing a PC as a “heterogeneous cluster in a box” is a big red button for people, in particular because “cluster” implies “parts can fail and program should continue.” So in the Q&amp;A, one commenter made the point that I should have mentioned reliability is an issue.</p>
<p>As I answered there, I half agree – it’s true but it’s only half the story, and it doesn’t affect the programming model (see more below). One of the slides I omitted to shorten this version of the talk highlighted that there are actually two issues when you go from “Disjoint (tightly coupled)” to “Disjoint (loosely coupled)”: <strong>reliability</strong> <em>and </em><strong>latency</strong>, and both are important. (I also mentioned this in the <a href="http://herbsutter.com/welcome-to-the-jungle/">original WttJ article</a> this is based on; just search for “reliability.”)</p>
<p>Even after the talk, I still got strong resistance along the lines that, ‘no, you obviously don’t get it, latency isn’t a significant issue at all, reliability is the central issue and it kills your argument because it makes the model fundamentally different.’ Paraphrasing subsequent email:</p>
<blockquote><p>‘A fundamental difference between distributed computing and single-box multiprocessing is that in the former case you don&#8217;t know whether a failure was a communication failure (i.e. the task was completed but communication failed) or a genuine failure to carry the task. (Hence all complicated two-phase commit protocols etc.) In contrast, in a single-box scenario you can know the box you&#8217;re on is working.’</p>
</blockquote>
<p>Let me respond further to this here, because clearly these guys know more about distributed systems than I do and I’m always happy to be educated, but I also think we have a disconnect on three things asserted above: It is not my understanding that reliability is more important than latency, or that apps have to distinguish comms failures from app exceptions, or that N-phase commit enters the picture.</p>
<p>First, I don’t agree with the assertion that reliability alone is what’s important, or that it’s more important than latency, for the following reason:</p>
<ul>
<li><strong>You can build reliable transports on top of unreliable ones.</strong> You do it through techniques like sequencing, redundancy, and retry. A classic example is <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a>, which delivers reliable communications over notoriously- and deliberately-unreliable IP which can drop and reorder packets as network nodes and communications paths keep madly appearing and reappearing like a herd of crazed Cheshire cats. We can and do build secure reliable global banking systems on that.</li>
<li><strong>Once you do that, you have turned a reliability issue into a performance (specifically latency) issue.</strong> Both reliability and latency are key issues when moving to loosely-coupled systems, but because you can turn the first into the second, it’s latency that is actually the more fundamental and important one – and the only one the developer needs to deal with.</li>
</ul>
<p>For example, to use compute clouds like Azure and AWS, you usually start with two basic pieces:</p>
<ul>
<li>the queue(s), which you use to push the work items out/around and results back/around; and </li>
<li>an elastic set of compute nodes, each of which pulls work items from the queue and processes them.</li>
</ul>
<p>What happens when you encounter a reliability problem? A node can pull a work item but fail to complete it, for example if the node crashes or the system encounters a partial network outage or other communication problem.</p>
<p>Many modern systems already automatically recover and have another node re-pull the same work item to make sure each work item gets done even in the face of partial failures. From the app&#8217;s point of view, such <strong>failures just manifest as degraded performance (higher latency or time-to-solution) and therefore mainly affect the granularity of parallel work items</strong> – they have to be big enough to be worth sending elsewhere and so minimum size is directly proportional to latency so that the overheads do not dominate. They do not manifest as app-visible failures.</p>
<p>Yes, the elastic cloud implementation has to deal with things like network failures and retries. But no, this isn’t your problem; it’s not supposed to be your job to implement the elastic cloud, it’s supposed to be your job just to implement each node’s local logic and to create whatever queues you want and push your work item data into them.</p>
<p>Aside: Of course, as with any retry-based model, you have to make sure that a partly-executed work item doesn’t expose any partial side effects it shouldn’t, and normally you prevent that by doing the work in a transaction and rolling it back on failure, or in the extreme (not generally recommended but sometimes okay) resorting to compensating writes to back out partial work. </p>
<p>That covers everything except the comment about two-phase commit: Citing that struck me as odd because I haven’t heard much us of that kind of coupled approach in years. Perhaps I’m misinformed, but my impression of 2- or N-phase commit protocols was that they have some serious problems: </p>
<ul>
<li>They are inherently nonscalable. </li>
<li>They increase rather than decrease interdependencies in the system – even with heroic efforts like majority voting and such schemes that try to allow for subsets of nodes being unavailable, which always seemed fragile to me. </li>
<li>Also, I seem to remember that NPC is a blocking protocol, which if so is inherently anti-concurrency. One of the big realizations in modern mainstream concurrency in the past few years is that Blocking Is Nearly Always Evil. (I’m looking at you, <em>future.get()</em>, and this is why the committee is now considering adding the nonblocking <em>future.then()</em> as well.)</li>
</ul>
<p>So my impression is that these were primarily of historical interest – if they are still current in modern datacenters, I would appreciate learning more about it and seeing if I’m overly jaded about N-phase commit.</p>
<br />Filed under: <a href='http://herbsutter.com/category/cloud/'>Cloud</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/hardware/'>Hardware</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>, <a href='http://herbsutter.com/category/talks-events/'>Talks &amp; Events</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1572&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/21/talk-video-welcome-to-the-jungle-60-min-version-qa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>

		<media:content url="http://herbsutter.files.wordpress.com/2012/06/image.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #105: Smart Pointers, Part 3 (Difficulty: 7/10)</title>
		<link>http://herbsutter.com/2012/06/05/gotw-105-smart-pointers-part-3-difficulty-710/</link>
		<comments>http://herbsutter.com/2012/06/05/gotw-105-smart-pointers-part-3-difficulty-710/#comments</comments>
		<pubDate>Tue, 05 Jun 2012 19:10:01 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1567</guid>
		<description><![CDATA[JG Question 1. What are the performance and correctness implications of the following function declaration? Explain. &#160; Guru Question 2. A colleague is writing a function f that takes an existing object of type widget as a required input-only parameter, and trying to decide among the following basic ways to take the parameter (omitting const): [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1567&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h3>JG Question</h3>
<p>1. What are the performance and correctness implications of the following function declaration? Explain.</p>
<p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a6d2ebea-842b-4a0a-8179-cab0a7ff2b75" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<pre style="white-space:normal;">
<pre class="brush: cpp; gutter: false; pad-line-numbers: true; title: ; notranslate">
void f( shared_ptr&lt;widget&gt; );
</pre>
</div>
<p>&#160;</p>
<h3>Guru Question</h3>
<p>2. A colleague is writing a function <em>f</em> that takes an existing object of type <em>widget</em> as a required input-only parameter, and trying to decide among the following basic ways to take the parameter (omitting <em>const</em>):</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:e9729faf-fb8d-4c47-8154-6c6d0bc2915f" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<pre style="white-space:normal;">
<pre class="brush: cpp; gutter: false; title: ; notranslate">
void f( widget&amp; );
void f( unique_ptr&lt;widget&gt; );
void f( unique_ptr&lt;widget&gt;&amp; );
void f( shared_ptr&lt;widget&gt; );
void f( shared_ptr&lt;widget&gt;&amp; );
</pre>
</div>
<p>Under what circumstances is each appropriate? Explain your answer, including where <em>const</em> should or should not be added anywhere in the parameter type.</p>
<p>(There are other ways to pass the parameter, but we will consider only the ones shown above.)</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1567&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/05/gotw-105-smart-pointers-part-3-difficulty-710/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>GotW #104: Solution</title>
		<link>http://herbsutter.com/2012/06/05/gotw-104-solution/</link>
		<comments>http://herbsutter.com/2012/06/05/gotw-104-solution/#comments</comments>
		<pubDate>Tue, 05 Jun 2012 19:03:20 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[GotW]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1565</guid>
		<description><![CDATA[The solution to GotW #104 is now live. Filed under: C++, GotW<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1565&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://herbsutter.com/gotw/_104/">The solution to GotW #104 is now live.</a></p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/c/gotw/'>GotW</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1565&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/05/gotw-104-solution/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>Facebook Folly &#8211; OSS C++ Libraries</title>
		<link>http://herbsutter.com/2012/06/02/facebook-folly-oss-c-libraries/</link>
		<comments>http://herbsutter.com/2012/06/02/facebook-folly-oss-c-libraries/#comments</comments>
		<pubDate>Sun, 03 Jun 2012 04:57:24 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1537</guid>
		<description><![CDATA[I’ve been beating the drum this year (see the last section of the talk) that the biggest problem facing C++ today is the lack of a large set of de jure and de facto standard libraries. My team at Microsoft just recently announced Casablanca, a cloud-oriented C++ library and that we intend to open source, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1537&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’ve been <a href="http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/C-11-VC-11-and-Beyond">beating the drum this year</a> (see the last section of the talk) that the biggest problem facing C++ today is the lack of a large set of <em>de jure</em> and <em>de facto</em> standard libraries. My team at Microsoft just recently announced <strong><a href="http://herbsutter.com/2012/04/30/c-libraries-casablanca/">Casablanca</a></strong>, a cloud-oriented C++ library and that we intend to open source, and we’re making other even bigger efforts that I hope will bear fruit and I’ll be able to share soon. But it can’t be just one company – many companies have already shared great open libraries on the past, but still more of us have to step up.</p>
<p>In that vein, I was extremely happy to see another effort come to fruition today. A few hours ago I was at Facebook to speak at their C++ day, and I got to be in the room when Andrei Alexandrescu dropped his arm to officially launch <strong><a href="https://www.facebook.com/notes/facebook-engineering/folly-the-facebook-open-source-library/10150864656793920">Folly</a></strong>:</p>
<blockquote><h4><font size="3"><a href="https://www.facebook.com/notes/facebook-engineering/folly-the-facebook-open-source-library/10150864656793920">Folly: The Facebook Open Source Library</a></font></h4>
<p>by <a href="http://www.facebook.com/delong.j">Jordan DeLong</a> on Saturday, June 2, 2012 at 2:59pm ·</p>
<p>Facebook is built on open source from top to bottom, and could not exist without it. As engineers here, we use, contribute to, and release a lot of open source software, including pieces of our core infrastructure such as <a href="https://github.com/facebook/hiphop-php">HipHop</a> and <a href="http://thrift.apache.org/">Thrift</a>.</p>
<p>But in our C++ services code, one clear bottleneck to releasing more work has been that any open sourced project needed to break dependencies on unreleased internal library code. To help solve that problem, today we open sourced an initial release of Folly, a collection of reusable C++ library artifacts developed and used at Facebook. This announcement was made at our C++ conference at Facebook in Menlo Park, CA.</p>
<p>Our primary aim with this &#8216;foolishness&#8217; is to create a solution that allows us to continue open sourcing parts of our stack without resorting to reinventing some of our internal wheels. And because Folly&#8217;s components typically perform significantly faster than counterparts available elsewhere, are easy to use, and complement existing libraries, we think C++ developers might find parts of this library interesting in their own right.</p>
</blockquote>
<p>Andrei announced that Folly stood for the <strong><font color="#0000ff">F</font></strong>acebook <strong><font color="#0000ff">O</font></strong>pen <strong><font color="#0000ff">Ll</font></strong>ibrar<strong><font color="#0000ff">y</font></strong>. He claimed it was a Welsh name, which is even funnier when said by a charming Romanian man.</p>
<p>Microsoft, and I personally, would like to congratulate Facebook on this release! Getting more high-quality open C++ libraries is a Good Thing, and I think it is safe to say that Casablanca and Folly are just the beginning. There’s a lot more coming&#160; across our industry this year. Stay tuned.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/cloud/'>Cloud</a>, <a href='http://herbsutter.com/category/concurrency/'>Concurrency</a>, <a href='http://herbsutter.com/category/software-development/'>Software Development</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1537&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/02/facebook-folly-oss-c-libraries/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
		<item>
		<title>We&#8217;re hiring (again &amp; more)</title>
		<link>http://herbsutter.com/2012/06/01/were-hiring-again-more/</link>
		<comments>http://herbsutter.com/2012/06/01/were-hiring-again-more/#comments</comments>
		<pubDate>Fri, 01 Jun 2012 23:04:27 +0000</pubDate>
		<dc:creator>Herb Sutter</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">https://herbsutter.wordpress.com/?p=1534</guid>
		<description><![CDATA[The Visual C++ team is looking for a number of people to do great work on C++11, parallelizing/vectorizing, cloud, libraries, and more. All I can say is that there’s a lot of cool stuff in the pipeline that directly addresses real needs, including things people regularly comment about on this blog that I can’t answer [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1534&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The Visual C++ team is looking for a number of people to do great work on C++11, parallelizing/vectorizing, cloud, libraries, and more. All I can say is that there’s a lot of cool stuff in the pipeline that directly addresses real needs, including things people regularly comment about on this blog that I can’t answer specifically yet but will soon.</p>
<p>If you might like to be part of it, here’s how – 13 positions right now and more to come as we update this list:</p>
<blockquote><p><strong><a href="http://blogs.msdn.com/b/vcblog/archive/2012/06/01/10313804.aspx">Be What’s Next (We’re hiring!)</a></strong></p>
<p>The C++ organization is growing and hiring across all feature areas (C++ 11, compiler front-end, compiler back-end, C++ AMP, PPL, libraries &amp; runtime, IDE, Casablanca). We are looking for passionate program managers, developers and testers to bang out the next versions of the toolset!</p>
<p>What’s in it for you:</p>
<ol>
<li>
<p>Be part of the C++ standards evolution &#8211; you’ll have the opportunity to work side-by-side with folks like Herb Sutter </p>
</li>
<li>
<p>Solve exciting challenges as we navigate the hardware evolution (newer chipsets, multi-core, GPU, heterogeneous cores etc.) </p>
</li>
<li>
<p>Be part of the technology that builds all of Microsoft’s platforms like Windows, Xbox, Windows Phone and Windows Embedded.</p>
</li>
</ol>
<p>Please apply directly using the links below. We’ll keep this list updated for the next couple of months.</p>
</blockquote>
<p>Current job list is available <a href="http://blogs.msdn.com/b/vcblog/archive/2012/06/01/10313804.aspx">on that page</a>.</p>
<br />Filed under: <a href='http://herbsutter.com/category/c/'>C++</a>, <a href='http://herbsutter.com/category/microsoft/'>Microsoft</a>  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=herbsutter.com&#038;blog=3379246&#038;post=1534&#038;subd=herbsutter&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://herbsutter.com/2012/06/01/were-hiring-again-more/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c0ba56bfd231f8f04feb057728975181?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Herb Sutter</media:title>
		</media:content>
	</item>
	</channel>
</rss>
