<?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>C++ on a Friday</title>
	<atom:link href="http://blog.knatten.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.knatten.org</link>
	<description>C++ fun and intricacies, updated every Friday morning</description>
	<lastBuildDate>Thu, 16 Feb 2012 08:50:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.knatten.org' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/901ae7d1746325ffee106051c01f4f1f?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>C++ on a Friday</title>
		<link>http://blog.knatten.org</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.knatten.org/osd.xml" title="C++ on a Friday" />
	<atom:link rel='hub' href='http://blog.knatten.org/?pushpress=hub'/>
		<item>
		<title>Disempower Every Variable</title>
		<link>http://blog.knatten.org/2011/11/11/disempower-every-variable/</link>
		<comments>http://blog.knatten.org/2011/11/11/disempower-every-variable/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 06:00:45 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[readability]]></category>
		<category><![CDATA[scope]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=846</guid>
		<description><![CDATA[In which I argue you should reduce the circle of influence, and the ability to change, of every variable. The more a variable can do, the harder it is to reason about. If you want to change a single line of code involving the variable, you need to understand all its other uses. To make [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=846&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I argue you should reduce the circle of influence, and the ability to change, of every variable.</em></p>
<p>The more a variable can do, the harder it is to reason about. If you want to change a single line of code involving the variable, you need to understand all its other uses. To make your code more readable and maintainable, you should disempower all your variables as much as possible.</p>
<p>Here are two things you can do to minimize the power of a variable:</p>
<p><strong>1: Reduce its circle of influence (minimize the scope)</strong><br />
I once had to make a bugfix in a 400 line function, containing tens of for-loops. They all reused a single counter variable:<br />
<pre class="brush: cpp;">
{
  int i;
  (...)
  for (i = 0; i &lt; n; ++i) {
  }
  (...)
  for (i = 0; i &lt; n; ++i) {
  }
  //350 lines later...
  for (i = 0; i &lt; n; ++i) {
  }
}
</pre></p>
<p>When looking at a single for-loop, how am I to know that the value of <code>i</code> is not used after the specific loop I was working on? Someone might be doing something like</p>
<p><pre class="brush: cpp;">
for (i = 0; i &lt; n; ++i) {
}
some_array[i] = 23
</pre></p>
<p>or</p>
<p><pre class="brush: cpp;">
for (i = 0; i &lt; n; ++i) {
}
for (; i &lt; m; ++i) {
}
</pre></p>
<p>The solution here is of course to use a local variable to each for-loop (unless of course it actually <em>is</em> used outside of the loop):<br />
<pre class="brush: cpp;">
for (int i = 0; i &lt; n; ++i) {
}
for (int i = 0; i &lt; n; ++i) {
}
</pre></p>
<p>Now I can be sure that if I change <code>i</code> in one for-loop, it won&#8217;t affect the rest of the function.</p>
<p><strong>2: Take away its ability to change (make it <code>const</code>)</strong></p>
<p>(I have <a href="http://blog.knatten.org/2010/08/20/please-make-member-functions-const-whenever-possible/">blogged</a> about <code>const</code> <a href="http://blog.knatten.org/2010/09/03/a-summary-of-const-part-one/">a few</a> times <a href="http://blog.knatten.org/2010/09/10/show-me-your-signature-and-ill-tell-you-who-you-are/">before</a>. It is almost always a good idea to make everything that doesn&#8217;t need to change <code>const</code>.)</p>
<p>Making a local variable <code>const</code> helps the reader to reason about the variable, since he will instantly know that its value will never change:</p>
<p><pre class="brush: cpp;">
void foo() {
  const string key = getCurrentKey();
  (...) //Later...
  doSomethingWith(key);
  (...) //Even later...
  collection.getItem(key).process();
</pre></p>
<p>Here the reader knows that we are always working with the same key throughout <code>foo()</code>.</p>
<p><strong>In summary:</strong> Reduce the circle of influence (by reducing the scope) and take away the ability to change (by using <code>const</code>).</p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/846/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=846&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/11/11/disempower-every-variable/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Undefined Behaviour — Worse Than its Reputation?</title>
		<link>http://blog.knatten.org/2011/11/04/undefined-behaviour-%e2%80%94-worse-than-its-reputation/</link>
		<comments>http://blog.knatten.org/2011/11/04/undefined-behaviour-%e2%80%94-worse-than-its-reputation/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 06:00:15 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[undefined behaviour]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=869</guid>
		<description><![CDATA[Last week I wrote about The Difference Between Unspecified and Undefined Behaviour. This week I&#8217;d like to expand a bit more on the severity of undefined behaviour. If however you have a lot of time, instead go read A Guide to Undefined Behavior in C and C++ by John Regehr of the University of Utah, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=869&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last week I wrote about <a href="http://blog.knatten.org/2011/10/28/the-difference-between-unspecified-and-undefined-behaviour/">The Difference Between Unspecified and Undefined Behaviour</a>. This week I&#8217;d like to expand a bit more on the severity of undefined behaviour. If however you have a lot of time, instead go read <a href="http://blog.regehr.org/archives/213">A Guide to Undefined Behavior in C and C++</a> by John Regehr of the University of Utah, and then <a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">What Every C Programmer Should Know About Undefined Behavior</a> by Chris Lattner of the LLVM project, as they cover this material in much more depth (and a lot more words!) than I do here.</p>
<p>To expand on the example from last week, what is the output of this program?</p>
<p><pre class="brush: cpp;">
int main()
{
    int array[] = {1,2,3};
    cout &lt;&lt; array[3] &lt;&lt; endl;
    cout &lt;&lt; &quot;Goodbye, cruel world!&quot; &lt;&lt; endl;
}
</pre></p>
<p>A good guess would be a random integer on one line, then &#8220;Goodbye, cruel world!&#8221; on another line. A better guess would be that anything can happen on the first line, but then &#8220;Goodbye, cruel world!&#8221; for sure is printed. The answer is however that we can&#8217;t even know that, since <em>If any step in a program’s execution has undefined behavior, then the entire execution is without meaning.</em> <a href="http://blog.regehr.org/archives/213">[Regehr p.1]</a>.</p>
<p>This fact has two implications that I want to emphasize:</p>
<p><strong>1: An optimizing compiler can move the undefined operation to a different place than it is given in the source code</strong><br />
<a href="http://blog.regehr.org/archives/232">[Regehr p.3]</a> gives a good example of this:</p>
<p><pre class="brush: cpp;">
int a;

void foo (unsigned y, unsigned z)
{
  bar();
  a = y%z; //Possible divide by zero
}
</pre></p>
<p>What happens if we call <code>foo(1,0)</code>? You would think <code>bar()</code> gets called, and then the program crashes. The compiler is however allowed to reorder the two lines in <code>foo()</code>, and <a href="http://blog.regehr.org/archives/232">[Regehr p.3]</a> indeed shows that Clang does exactly this.</p>
<p>What are the implications? If you are investigating a crash in your program and never see the results of <code>bar()</code>, you might falsely conclude that the bug in the sourcecode must be before <code>bar()</code> is called, or in its very beginning. To find the real bug in this case you would have to turn off optimization, or step through the program in a debugger.</p>
<p><strong>2: Seemingly unrelated code can be optimized away near a possible undefined behaviour</strong><br />
<a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">[Lattner p.1]</a> presents a good example:</p>
<p><pre class="brush: cpp;">
void contains_null_check(int *P) {
  int dead = *P;
  if (P == 0)
    return;
  *P = 4;
}
</pre></p>
<p>What happens if <code>P</code> is <code>NULL</code>? Maybe some garbage gets stored in <code>int dead</code>? Maybe dereferencing <code>P</code> crashes the program? At least we can be sure that we will never reach the last line, <code>*P = 4</code> because of the check <code>if (P == 0)</code>. Or can we?</p>
<p>An optimizing compiler applies its optimizations in series, not in one omniscient operation. Imagine two optimizations acting on this code, &#8220;Redundant Null Check Elimination&#8221; and &#8220;Dead Code Elimination&#8221; (in that order).</p>
<p>During Redundant Null Check Elimination, the compiler figures that if <code>P == NULL</code>, then <code>int dead = *P;</code> results in undefined behaviour, and the entire execution is undefined. The compiler can basically do whatever it wants. If <code>P != NULL</code> however, there is no need for the <code>if</code>-check. So it safley optimizes it away:</p>
<p><pre class="brush: cpp;">
void contains_null_check(int *P) {
  int dead = *P;
  //if (P == 0)
    //return;
  *P = 4;
}
</pre></p>
<p>During Dead Code Elimination, the compiler figures out that <code>dead</code> is never used, and optimizes that line away as well. This invalidates the assumption made by Redundant Null Check Elimination, but the compiler has no way of knowing this, and we end up with this:</p>
<p><pre class="brush: cpp;">
void contains_null_check(int *P) {
  *P = 4;
}
</pre></p>
<p>When we wrote this piece of code, we were <em>sure</em> (or so we thought) that <code>*P = 4</code> would never be reached when <code>P == NULL</code>, but the compiler (correctly) optimized away the guard we meticulously had put in place.</p>
<p><strong>Concluding notes</strong><br />
If you thought undefined behaviour only affected the operation in which it appears, I hope I have convinced you otherwise. And if you found the topic interesting, I really recommend reading the two articles I mentioned in the beginning (<a href="http://blog.regehr.org/archives/213">A Guide to Undefined Behavior in C and C++</a> and <a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">What Every C Programmer Should Know About Undefined Behavior</a>). And the morale of the story is of course to avoid undefined behaviour like the plague.</p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/869/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/869/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/869/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=869&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/11/04/undefined-behaviour-%e2%80%94-worse-than-its-reputation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>The Difference Between Unspecified and Undefined Behaviour</title>
		<link>http://blog.knatten.org/2011/10/28/the-difference-between-unspecified-and-undefined-behaviour/</link>
		<comments>http://blog.knatten.org/2011/10/28/the-difference-between-unspecified-and-undefined-behaviour/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 06:00:07 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[undefined behaviour]]></category>
		<category><![CDATA[unspecified behaviour]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=827</guid>
		<description><![CDATA[What is the output of this program? Answer: Noone knows! What is the output of this program? Answer: Noone knows! There is a difference in the severity of uncertainty though. The first case results in undefined behaviour (because we are indexing outside of the array), whereas the second results in unspecified behaviour (because we don&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=827&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>What is the output of this program?</p>
<p><pre class="brush: cpp;">
int main()
{
    int array[] = {1,2,3};
    cout &lt;&lt; array[3] &lt;&lt; endl;
}
</pre></p>
<p><!-- snippetysnip_end:/home/anders/doc/blog/code/unspecified/undefined.cpp:undefined --></p>
<p><strong>Answer:</strong> Noone knows!</p>
<p>What is the output of this program?</p>
<p><pre class="brush: cpp;">
void f(int i, int j){}

int foo()
{
    cout &lt;&lt; &quot;foo &quot;;
    return 42;
}

int bar()
{
    cout &lt;&lt; &quot;bar &quot;;
    return 42;
}

int main()
{
    f(foo(), bar());
}
</pre></p>
<p><!-- snippetysnip_end:/home/anders/doc/blog/code/unspecified/unspecified.cpp:unspecified --></p>
<p><strong>Answer:</strong> Noone knows!</p>
<p>There is a difference in the severity of uncertainty though. The first case results in <em>undefined behaviour</em> (because we are indexing outside of the array), whereas the second results in <em>unspecified behaviour</em> (because we don&#8217;t know the order in which the function arguments will be evaluated). What is the difference?</p>
<p>In the case of <em>undefined</em> behaviour, we are screwed. Anything can happen, from what you thought should happen, to the program sending threatening letters to your neighbour&#8217;s cat. Probably it will read the memory right after where the array is stored, interpret whatever garbage is there and print it, but there is no way to know this.</p>
<p>In the case of <em>unspecified</em> behaviour however, we are probably OK. The implementation is allowed to choose from a set of well-defined behaviours. In our case, there are two possibilities, calling <code>foo()</code> then <code>bar()</code>, or <code>bar()</code> then <code>foo()</code>. Note that if <code>foo()</code> and <code>bar()</code> have some side-effects that we rely on being executed in a specific order, this unspecified behaviour would still mean we have a bug in our code.</p>
<p>To summarize, <em>never</em> write code that results in undefined behaviour, and never write code that relies on unspecified behaviour.</p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/827/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/827/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/827/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=827&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/10/28/the-difference-between-unspecified-and-undefined-behaviour/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Don&#8217;t be Afraid of Returning by Value, Know the Return Value Optimization</title>
		<link>http://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/</link>
		<comments>http://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 06:00:28 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[return value optimization]]></category>
		<category><![CDATA[rvo]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=797</guid>
		<description><![CDATA[In which I argue you shouldn&#8217;t be afraid of returning even large objects by value. If you have somewhat large collections of somewhat large objects in a performance-critical application, which of the following functions would you prefer? The first version looks faster, right? After all, the second one returns a copy of the vector, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=797&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I argue you shouldn&#8217;t be afraid of returning even large objects by value.</em></p>
<p>If you have somewhat large collections of somewhat large objects in a performance-critical application, which of the following functions would you prefer?</p>
<p><pre class="brush: cpp;">
void getObjects(vector&lt;C&gt;&amp; objs);
vector&lt;C&gt; getObjects();
</pre></p>
<p>The first version looks faster, right? After all, the second one returns a copy of the vector, and to do that, all the elements have to be copied. Sounds expensive! Better then, to pass inn a reference to a vector that is filled, and avoid the expensive return.</p>
<p>The second version is however easier to use, since it communicates more clearly what it does, and does not require the caller to define the vector to be filled. Compare<br />
<pre class="brush: cpp;">
    doSomethingWith(getObjects());
</pre></p>
<p>against the more cubmersome</p>
<p><pre class="brush: cpp;">
    vector&lt;C&gt; temp;
    getObjects(temp);
    doSomethingWith(temp);
</pre></p>
<p>Sounds like a classic tradeoff between speed and clarity then. Except it isn&#8217;t! Both functions incur the exact same number of copies, even on the lowest optimization levels, and without inlining anything. How is that possible? The answer is the Return Value Optimization (RVO), which allows the compiler to optimize away the copy by having the caller and the callee use the same chunk of memory for both &#8220;copies&#8221;.</p>
<p>If you got the point, and take my word for it, you can stop reading now. What follows is a somewhat lengthy example demonstrating the RVO being used in several typical situations.</p>
<p><strong>Example</strong><br />
Basically, I have a <code>class C</code>, which counts the times it is constructed or copy constructed, and a library of functions that demonstrate slightly different ways of returning instances of <code>C</code>.</p>
<p>Here are the getter functions:</p>
<p><pre class="brush: cpp;">
C getTemporaryC() {
	return C();
}

C getLocalC() {
	C c;
	return c;
}

C getDelegatedC() {
	return getLocalC();
}

vector&lt;C&gt; getVectorOfC() {
	vector&lt;C&gt; v;
	v.push_back(C()); 
	return v;
}

</pre></p>
<p>I then call each of these functions, measuring the number of constructors and copy constructors called:</p>
<p><pre class="brush: cpp;">
int main() {
	C c1;
	print_copies(&quot;1: Constructing&quot;);

	C c2(c1);
	print_copies(&quot;2: Copy constructing&quot;);

	C c4 = getTemporaryC();
	print_copies(&quot;3: Returning a temporary&quot;);

	C c5 = getLocalC();
	print_copies(&quot;4: Returning a local&quot;);

	C c6 = getDelegatedC();
	print_copies(&quot;5: Returning through a delegate&quot;);

	vector&lt;C&gt; v = getVectorOfC();
	print_copies(&quot;6: Returning a local vector&quot;);
}
</pre></p>
<p><em>Update: I used gcc 4.5.2 to test this. Since then, people have tested using other compilers, getting less encouraging results. Please see the comments, and the summary table near the end.</em></p>
<p>This is the result:</p>
<p><code>1: Constructing used 0 copies, 1 ctors.<br />
2: Copy constructing used 1 copies, 0 ctors.<br />
3: Returning a temporary used 0 copies, 1 ctors.<br />
4: Returning a local used 0 copies, 1 ctors.<br />
5: Returning through a delegate used 0 copies, 1 ctors.<br />
6: Returning a local vector used 1 copies, 1 ctors.<br />
</code></p>
<p><strong>Discussion</strong><br />
<em>1</em> and <em>2</em> are just there to demonstrate that the counting works. In <em>1</em>, the constructor is called once, and in <em>2</em> the copy constructor is called once.</p>
<p>Then we get to the interesting part; In <em>3</em> and <em>4</em>, we see that returning a copy does not invoke the copy constructor, even when the initial <code>C</code> is allocated on the heap in a local variable.</p>
<p>Then we get to <em>5</em>, which also returns by value, but where the initial vector is not allocated by the function itself. Rather, it gets its vector from calling yet antother function. Even this chaining of methods doesn&#8217;t defeat the RVO, there are still not a single copy being made.</p>
<p>Finally, in <em>6</em>, we try returing a container, a <code>vector&lt;C&gt;</code>. Aha! A copy was made! But the copy that gets counted is made by <code>vector::push_back()</code>, not by returning the vector. So we see that the RVO also works when returning containers.</p>
<p><strong>A curious detail</strong><br />
The normal rule for optimization used by the C++ standard is that the compiler is free to use whatever crazy cheating tricks it can come up with, <em>as long as the result is no different from the non-optimized code</em>. Can you spot where this rule is broken? In my example, the copy constructor has a side effect, incrementing the counter of copies made. That means that if the copy is optimized away, the result of the program is now different with and without RVO! This it what makes the RVO different from other optimizations, in that the compiler is actually allowed to optimize away the copy constructor <em>even if it has side effects</em>.</p>
<p><strong>Conclusion</strong><br />
This has been my longest post so far, but the conclusion is simple: Don&#8217;t be afraid of returning large objects by value! Your code will be simpler, and just as fast.</p>
<p><em>UPDATE:</em> Several people have been nice enough to try the examples in various compilers, here is a summary of the number of copies made in examples 3-6:</p>
<table>
<tr>
<th>Compiler</th>
<th>Temporary</th>
<th>Local</th>
<th>Delegate</th>
<th>Vector</th>
<th>SUM</th>
<th>Contributed by</th>
</tr>
<tr>
<td>GCC 4.4.5</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>Anders S. Knatten</td>
</tr>
<tr>
<td>GCC 4.5.2</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>Anders S. Knatten</td>
</tr>
<tr>
<td>GCC 4.5.2 -std=c++0x</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>Anders S. Knatten</td>
</tr>
<tr>
<td>Visual Studio 2008</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>Anders S. Knatten</td>
</tr>
<tr>
<td>Sun C++ 5.8 Patch 121017-14 2008/04/16</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
<td>Bruce Stephens</td>
</tr>
<tr>
<td>Sun C++ 5.11 SunOS_i386 2010/08/13</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
<td>Asgeir S. Nilsen</td>
</tr>
<tr>
<td>HP ANSI C++ B3910B A.03.85</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>2</td>
<td>5</td>
<td>Bruce Stephens</td>
</tr>
</table>
<p><em>You can download all the example code from this post at <a href="https://github.com/knatten/blog.knatten.org/tree/master/rvo">Github</a>.</em></p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/797/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=797&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Use boost list_of if You Can&#8217;t Have Uniform Initialization Yet</title>
		<link>http://blog.knatten.org/2011/08/19/use-boost-list_of-if-you-cant-have-uniform-initialization-yet/</link>
		<comments>http://blog.knatten.org/2011/08/19/use-boost-list_of-if-you-cant-have-uniform-initialization-yet/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 06:00:57 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[assign]]></category>
		<category><![CDATA[boost]]></category>
		<category><![CDATA[initialization]]></category>
		<category><![CDATA[list_of]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=782</guid>
		<description><![CDATA[In which I demonstrate how boost::assign::list_of simplifies initialization of containers. I have previously blogged about how Uniform Initialization Simplifies Testing. In C++, you can initialize an array when defining it, but you can not initialize containers: You have to resort to something like this: In C++0X, we will have Uniform Initialization to take care of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=782&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I demonstrate how <code>boost::assign::list_of</code> simplifies initialization of containers.</em></p>
<p>I have previously blogged about how <a href="http://blog.knatten.org/2011/03/25/uniform-initialization-simplifies-testing/">Uniform Initialization Simplifies Testing</a>. In C++, you can initialize an array when defining it, but you can not initialize containers:</p>
<p><pre class="brush: cpp;">
	int a[] = {1, 2, 3}; //OK
	vector&lt;int&gt; v = {1, 2, 3}; //Not OK
</pre></p>
<p>You have to resort to something like this:</p>
<p><pre class="brush: cpp;">
	//Either
	vector&lt;int&gt; v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);

	//Or
	int tmp[] = {1, 2, 3}; 
	vector&lt;int&gt; v2(tmp, tmp+3);
</pre></p>
<p>In <a href="http://en.wikipedia.org/wiki/C_0x">C++0X</a>, we will have <a href="http://en.wikipedia.org/wiki/C_0x#Uniform_initialization">Uniform Initialization</a> to take care of this, but if you are not on a supported compiler yet, you can use <a href="http://www.boost.org/doc/libs/1_47_0/libs/assign/doc/index.html#list_of">boost::assign</a> while you are waiting:</p>
<p><pre class="brush: cpp;">
	vector&lt;int&gt; v3 = boost::assign::list_of(1)(2)(3);
</pre></p>
<p>This is, again, especially useful in testing. To translate the example from <a href="http://blog.knatten.org/2011/03/25/uniform-initialization-simplifies-testing/">my last post</a> from C++0X to C++98 with boost:</p>
<p><pre class="brush: cpp;">
using boost::assign::list_of;
 
int count_sheep(const vector&lt;string&gt;&amp; animals) {
	return count(animals.begin(), animals.end(), &quot;sheep&quot;);
}
 
TEST(TestCountSheep, returns_zero_when_there_are_no_sheep) {
	ASSERT_EQ(0, count_sheep(list_of(&quot;pig&quot;)(&quot;cow&quot;)(&quot;giraffe&quot;))); //here
}
	 
TEST(TestCountSheep, returns_all_sheep) {
	ASSERT_EQ(2, count_sheep(list_of(&quot;sheep&quot;)(&quot;cow&quot;)(&quot;sheep&quot;))); //and here
}
</pre></p>
<p>To use <code>boost::assign</code>, make sure to <code>#include &lt;boost/assign.hpp&gt;</code>. It has other clever tricks as well, so be sure to check out <a href="http://www.boost.org/doc/libs/1_47_0/libs/assign/doc/index.html#list_of">the docs</a>. Boost is a widely used collection of high quality libraries for C++, and can be <a href="http://www.boost.org/users/download/">downloaded here</a>.</p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/782/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/782/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/782/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=782&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/08/19/use-boost-list_of-if-you-cant-have-uniform-initialization-yet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Modify Visibility in a Subclass to Allow Testing</title>
		<link>http://blog.knatten.org/2011/08/12/modify-visibility-in-a-subclass-to-allow-testing/</link>
		<comments>http://blog.knatten.org/2011/08/12/modify-visibility-in-a-subclass-to-allow-testing/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 06:00:47 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[visibility]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=736</guid>
		<description><![CDATA[In which I argue it might sometimes be useful to test private/protected methods, and demonstrate how to do it in a framework-independent way. How do you test private/protected functions? The most common, and often correct answer is &#8220;Don&#8217;t!&#8221;. But sometimes it can be useful, especially when test-driving helper-methods. Example: This will fail: error: ‘int Ohlson::helper()’ [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=736&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I argue it might sometimes be useful to test private/protected methods, and demonstrate how to do it in a framework-independent way.</em></p>
<p>How do you test private/protected functions? The most common, and often correct answer is <em>&#8220;Don&#8217;t!&#8221;</em>. But sometimes it can be useful, especially when test-driving helper-methods. Example:</p>
<p><pre class="brush: cpp;">
class Ohlson {
protected:
	int helper(); //We want to test this
public:
	int compute() {
		//(...)
		int n = helper();
		//(...)
	}
};


TEST(TestOhlson, helper_returns42) {
	Ohlson o;
	ASSERT_EQ(42, o.helper());
}
</pre></p>
<p>This will fail: <code>error: ‘int Ohlson::helper()’ is protected</code>. Many unittesting frameworks provide a way to work around this, like googletest&#8217;s <a href="http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code" title="FRIEND_TEST">FRIEND_TEST</a>, but there is a way to get around this in normal C++, by subclassing to modify visibility.</p>
<p>In C++, a subclass can change the visibility of a derived function. This is not possible in Java or C# as far as I know, and to be honest it does sound somewhat dangerous. But C++ wasn&#8217;t made to keep you in a padded box with a helmet on, was it?</p>
<p>Here&#8217;s how you do it:<br />
<pre class="brush: cpp;">
class OhlsonForTest : public Ohlson {
public:
	using Ohlson::helper;
};
</pre></p>
<p>And voilà, <code>helper()</code> is now public and can be tested:</p>
<p><pre class="brush: cpp;">
TEST(TestOhlson, helper_returns42) {
	OhlsonForTest o;
	ASSERT_EQ(42, o.helper());
}
</pre></p>
<p>This trick can be useful in some situations, but when you are done, see if you might refactor your way out of the problem instead.</p>
<p>And I would be extremely sceptical to do anything like this in production code!</p>
<p><em>By the way, this trick is often useful in combination with last weeks technique on <a href="http://blog.knatten.org/2011/08/05/make-a-derived-class-to-allow-testing-an-abstract-class/">Making a Derived Class to Allow Testing an Abstract Class</a>.</em></p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to this blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/736/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=736&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/08/12/modify-visibility-in-a-subclass-to-allow-testing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Make a Derived Class to Allow Testing an Abstract Class</title>
		<link>http://blog.knatten.org/2011/08/05/make-a-derived-class-to-allow-testing-an-abstract-class/</link>
		<comments>http://blog.knatten.org/2011/08/05/make-a-derived-class-to-allow-testing-an-abstract-class/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 06:00:47 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[virtual]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=738</guid>
		<description><![CDATA[In which I show how best to test an abstract class, which normally wouldn&#8217;t be instantiatable. Abstract classes are not instantiatable, so how do you test one? Say you want to test Abstract::common(), like so: It&#8217;s not possible, because common() special() is pure virtual (it has no implementation in Abstract). So how do you test [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=738&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I show how best to test an abstract class, which normally wouldn&#8217;t be instantiatable.</em></p>
<p>Abstract classes are not instantiatable, so how do you test one?</p>
<p><pre class="brush: cpp;">
class Abstract
{
public:
	int common();
	virtual int special() = 0;
};

class Concrete : public Abstract
{
public:
	int special();
};
</pre></p>
<p>Say you want to test <code>Abstract::common()</code>, like so:<br />
<pre class="brush: cpp;">
TEST(TestAbstract, helper_returns42)
{
	Abstract abs; //cannot declare variable ‘abs’ to be of abstract type ‘Abstract’
	ASSERT_EQ(42, abs.common());
}
</pre></p>
<p>It&#8217;s not possible, because <code><del datetime="2011-08-08T06:07:39+00:00">common()</del> special()</code> is pure virtual (it has no implementation in <code>Abstract</code>). So how do you test a class that cannot be instantiated? It can be tempting to test through a concrete subclass:</p>
<p><pre class="brush: cpp;">
TEST(TestAbstract, common_returns42)
{
	Concrete abs; 
	ASSERT_EQ(42, abs.common());
}
</pre></p>
<p>But this is generally a bad idea, since <code>Concrete</code> might change the behaviour of <code>common()</code>. Even though it is not virtual, it operates under a different state. And even though you <em>know</em> it will work now, you don&#8217;t know how <code>Concrete</code> will change in the future, and then you don&#8217;t want tests that don&#8217;t have anything to do with <code>Concrete</code> to start failing. Also, creating a <code>Concrete</code> object when you are testing on <code>Abstract</code> is confusing to the reader.</p>
<p>Instead, I recommend you derive a class to be used just for testing:</p>
<p><pre class="brush: cpp;">

class AbstractForTest : public Abstract {
	int special();
};

TEST(TestAbstract, common_returns42)
{
	AbstractForTest abs; 
	ASSERT_EQ(42, abs.common());
}
</pre></p>
<p>In this way you get rid of the unwanted dependency, and the test is easier to understand. As a final note, make sure you name your test-class something that clearly distinguishes it as a testing artifact, like I did above. Also make sure to keep it in your test code (e.g. TestAbstract.cpp), not in your production code (e.g. Abstract.h/.cpp).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/738/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/738/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/738/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=738&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/08/05/make-a-derived-class-to-allow-testing-an-abstract-class/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>The Minesweeper Kata in 15 lines of C++</title>
		<link>http://blog.knatten.org/2011/04/01/the-minesweeper-kata-in-15-lines-of-c/</link>
		<comments>http://blog.knatten.org/2011/04/01/the-minesweeper-kata-in-15-lines-of-c/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 07:00:24 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[kata]]></category>
		<category><![CDATA[lambda functions]]></category>
		<category><![CDATA[minesweeper]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=711</guid>
		<description><![CDATA[In which I solve the Minesweeper Kata using c++0x lambdas and a little thinking outside the box (literally). A few days ago I went to see Prepared Katas at Communities in Action, in which four guys solved minesweeper in Ruby, Perl, Java and Javascript. They had just 20 minutes to code and test, which is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=711&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I solve the Minesweeper Kata using c++0x lambdas and a little thinking outside the box (literally).</em></p>
<p>A few days ago I went to see <a href="http://www.meetup.com/OsloCodingDojo/events/16757504/">Prepared Katas at Communities in Action</a>, in which four guys solved minesweeper in Ruby, Perl, Java and Javascript. They had just 20 minutes to code and test, which is short even for a prepared kata. They all looked pretty stressed out, except for the Perl guy who looked smug. But that&#8217;s how they always look, isn&#8217;t it?</p>
<p>Anyway, I thought I&#8217;d try the kata in C++, and see if I could golf it a bit without sacrificing readability too much. I ended up solving it in <del>15</del> 12 lines, expanded a bit here for readability.</p>
<p>I use two tricks that I should mention before I show you the code:</p>
<p>The first is to expand the board by one in each direction. That is, if the board is 3&#215;3, I allocate a 5&#215;5 scratch board. In this way, each cell can check all it&#8217;s neighbours without special handling of the edge cases.</p>
<p>The second trick is not really a trick, but I should mention it anyway, since most C++ developers won&#8217;t be familiar with it. I am using <a href="http://en.wikipedia.org/wiki/C_0x#Lambda_functions_and_expressions">C++0x lambda functions</a>, which work nicely with the normal stl algorithms.</p>
<p>But let&#8217;s get to the point, here&#8217;s the code:<br />
<pre class="brush: cpp;">
vector&lt;string&gt; solve(vector&lt;string&gt; board) {
	int rows = board.size();
	int cols = board[0].size();
	char* big_board = static_cast&lt;char*&gt;(calloc((rows+2)*(cols+2), sizeof(char))); //Supersized board

	for (int r = 0; r &lt; rows; ++r)  //Put 1 in each mine-cell
		transform(board[r].begin(), board[r].end(), &amp;big_board[(r+1)*(cols+2)+1],
			[](char c) {return (c == '*');});

	vector&lt;string&gt; solution(rows);
	for (int r = 0; r &lt; rows; ++r)  //Calculate solution
		transform(&amp;big_board[(r+1)*(cols+2)+1], &amp;big_board[(r+1)*(cols+2)+cols+1], back_inserter(solution[r]),
			[=](char&amp;c){ return (c ? '*' : '0'
				+ *(&amp;c-cols-3) + *(&amp;c-cols-2) + *(&amp;c-cols-1) //Previous row
				+ *(&amp;c-1) + *(&amp;c+1) //This row
				+ *(&amp;c+cols+1) + *(&amp;c+cols+2) + *(&amp;c+cols+3));}); //Next row
	free(big_board);
	return solution;
}
</pre></p>
<p><em>Update 10 April: Thanks <a href="http://meekrosoft.wordpress.com/">Mike Long</a> for golfing off another line using <code>calloc</code> instead of <code>new</code> and <code>fill</code>, and having me fix the memory leak.</em></p>
<p>You need G++ 4.5 to compile this (<code>sudo apt-get install g++-4.5</code>). Compile with <code>g++-4.5 -std=c++0x</code></p>
<p>I also uploaded a tarball with the full code, including unittests and a make-script, <a href="http://knatten.org/download/minesweeper.tgz">here</a>.</p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a>.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/711/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=711&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/04/01/the-minesweeper-kata-in-15-lines-of-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>Uniform Initialization Simplifies Testing</title>
		<link>http://blog.knatten.org/2011/03/25/uniform-initialization-simplifies-testing/</link>
		<comments>http://blog.knatten.org/2011/03/25/uniform-initialization-simplifies-testing/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 21:09:47 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[containers]]></category>
		<category><![CDATA[googletest]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[uniform initialization]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=694</guid>
		<description><![CDATA[In which I demonstrate the use of uniform initialization, and show how it is particularly well suited to unit tests. In C++0x, there is Yet Another Way to initialize objects, using the {} syntax (uniform initialization). Except, it isn&#8217;t really new, it&#8217;s the way we&#8217;ve always been initializing arrays and structs: The difference is we [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=694&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>In which I demonstrate the use of uniform initialization, and show how it is particularly well suited to unit tests.</em></p>
<p>In C++0x, there is Yet Another Way to initialize objects, using the <code>{}</code> syntax (<a href="http://en.wikipedia.org/wiki/C_0x#Uniform_initialization">uniform initialization)</a>. Except, it isn&#8217;t really new, it&#8217;s the way we&#8217;ve always been initializing arrays and structs:</p>
<p><pre class="brush: cpp;">
int i[] = {1,4,9};
</pre></p>
<p>The difference is we can now use this syntax to initialize any object. Why does this matter, and what is wrong with the old constructor syntax? Nothing is wrong with it in fact, and it will still see a lot of use. But in some cases, <code>{}</code> leads to simpler and easier code.</p>
<p>One area in particular is initialization of containers. It was always a bit of a hassle to initialize for instance a vector, where you would need to do something like this:</p>
<p><pre class="brush: cpp;">
    string a[] = {&quot;foo&quot;, &quot;bar&quot;};
    vector&lt;string&gt; v(a, a+2);
</pre></p>
<p>In C++0x however, you can do</p>
<p><pre class="brush: cpp;">
    vector&lt;string&gt; v = {&quot;foo&quot;, &quot;bar&quot;};
</pre></p>
<p>One area where I find myself initializing containers manually a lot is in unit tests. Here is an example:</p>
<p><pre class="brush: cpp;">
#include &lt;gtest/gtest.h&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using namespace std;

int count_sheep(const vector&lt;string&gt;&amp; animals) {
    return count(animals.begin(), animals.end(), &quot;sheep&quot;);
}

TEST(TestCountSheep, returns_zero_when_there_are_no_sheep) {
    ASSERT_EQ(0, count_sheep({&quot;pig&quot;, &quot;cow&quot;, &quot;giraffe&quot;})); //here
}

TEST(TestCountSheep, returns_all_sheep) {
    ASSERT_EQ(2, count_sheep({&quot;sheep&quot;, &quot;cow&quot;, &quot;sheep&quot;})); //and here
}

</pre></p>
<p>Note the calls to <code>count_sheep()</code>, where the container is declared and initialized in line, without any mention of <code>string</code>, <code>vector</code> or temporary arrays!</p>
<p>To compile this, you need g++ 4.5 (<code>sudo apt-get install g++-4.5</code>). It might also be possible in Visual Studio 2010 if you are so inclined. This example also uses the <a href="http://code.google.com/p/googletest/">Google C++ Testing Framework</a> (<code>sudo apt-get install libgtest-dev</code>). Here is the full command to compile and run the example:<br />
<code><br />
g++-4.5 * -std=c++0x -lgtest_main -lgtest -lpthread &amp;&amp; ./a.out<br />
</code></p>
<p><em>If you enjoyed this post, you can <a href="http://blog.knatten.org/feed/">subscribe to my blog</a>, or <a href="http://twitter.com/#!/knatten">follow me on Twitter</a></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/694/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=694&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/03/25/uniform-initialization-simplifies-testing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
		<item>
		<title>What I&#8217;ve Been Working On</title>
		<link>http://blog.knatten.org/2011/01/10/what-ive-been-working-on/</link>
		<comments>http://blog.knatten.org/2011/01/10/what-ive-been-working-on/#comments</comments>
		<pubDate>Mon, 10 Jan 2011 19:52:57 +0000</pubDate>
		<dc:creator>Anders Schau Knatten</dc:creator>
				<category><![CDATA[Off topic]]></category>

		<guid isPermaLink="false">http://blog.knatten.org/?p=686</guid>
		<description><![CDATA[The reason for me taking a hiatus was as I said because I was building something. That something is as of now in public beta, at riktigbil.no. The site is Norway&#8217;s only priceguide for new cars, and was written in Python/Django. It is a bit off topic for this blog of course, but I thought [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=686&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The reason for me taking <a href="http://blog.knatten.org/2010/11/17/i-am-taking-a-hiatus/">a hiatus</a> was as I said because I was building something. That something is as of now in public beta, at <a href="http://riktigbil.no">riktigbil.no</a>.</p>
<p>The site is Norway&#8217;s only priceguide for new cars, and was written in Python/Django. It is a bit off topic for this blog of course, but I thought I&#8217;d let you know what I&#8217;ve been working on!</p>
<p>If you are in Norway and looking for a new car, <a href="http://riktigbil.no">riktigbil.no</a> is the place to look! :) Any feedback is of course most appreciated, either here or by email to post@riktigbil.no. Thanks!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aknatten.wordpress.com/686/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aknatten.wordpress.com/686/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aknatten.wordpress.com/686/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.knatten.org&amp;blog=12689027&amp;post=686&amp;subd=aknatten&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.knatten.org/2011/01/10/what-ive-been-working-on/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/787eddb4ebc55d8f34ebe88551d55a0b?s=96&#38;d=identicon&#38;r=X" medium="image">
			<media:title type="html">aknatten</media:title>
		</media:content>
	</item>
	</channel>
</rss>
