<?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/"
	>

<channel>
	<title>Dysfunctional Programming &#187; C++</title>
	<atom:link href="http://ra3s.com/wordpress/dysfunctional-programming/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://ra3s.com/wordpress/dysfunctional-programming</link>
	<description>(λ (a b) a) vs (λ (a b) b)</description>
	<lastBuildDate>Wed, 25 Jan 2012 17:05:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Concepts: Typeclasses for C++?</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/concepts-typeclasses-for-cpp/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/concepts-typeclasses-for-cpp/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 05:01:00 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[concepts]]></category>
		<category><![CDATA[generic programming]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=377</guid>
		<description><![CDATA[I&#8217;ve had a hypothesis for a while that C++ templates (paired at times with ADL) are an ad-hoc, unsound version of typeclasses. I&#8217;ve seen this hold for parser combinators, range base algorithms, and more. I&#8217;m also not the first to draw &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/concepts-typeclasses-for-cpp/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had a hypothesis for a while that C++ templates (paired at times with <a href="http://en.wikipedia.org/wiki/Argument-dependent_name_lookup">ADL</a>) are an ad-hoc, unsound version of typeclasses. I&#8217;ve seen this hold for <a href="http://parsnip-parser.sourceforge.net/">parser combinators</a>, <a href="http://www.boost.org/doc/libs/1_48_0/libs/range/doc/html/index.html">range base algorithms</a>, and more. I&#8217;m also not the first to draw this comparison[<a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.78.2151">1</a>].</p>
<p><a href="http://en.wikipedia.org/wiki/Concepts_(C%2B%2B)">Concepts</a> are supposed to bring soundness in through constrained templates. Concepts look awfully a lot like type classes; they export functions and types, and are parameterized, and act as constraints on generic functions and other concepts. I checked the draft specification [<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2617.pdf">2</a>], and it even seems to permit parameterizing concepts on type constructors, just like Haskell! (er, C++ calls them class templates, not type constructors. <a href="http://en.wiktionary.org/wiki/tomato_tomato#Phrase">to-<em>may-</em>to, to-<em>mah-</em>to</a>)</p>
<p>But I worried I may be mistaken about concepts, as I&#8217;ve searched through google and literature and have yet to find a single example in literature demonstrating the use of template template concepts.</p>
<p>In case you&#8217;re curious what this might look like, here&#8217;s an educated guess:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">concept Monad<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">class</span> m<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span> U<span style="color: #000080;">&gt;</span>
  m<span style="color: #000080;">&lt;</span>U<span style="color: #000080;">&gt;</span> mbind<span style="color: #008000;">&#40;</span>m<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span>, function<span style="color: #000080;">&lt;</span>m<span style="color: #000080;">&lt;</span>U<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>T<span style="color: #008000;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
  <span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">class</span> T<span style="color: #000080;">&gt;</span>
  m<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> mreturn<span style="color: #008000;">&#40;</span>T<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">class</span> m,
          <span style="color: #0000ff;">class</span> T,
          <span style="color: #0000ff;">class</span> U,
          <span style="color: #0000ff;">class</span> Iter<span style="color: #000080;">&gt;</span>
requires M<span style="color: #000080;">&lt;</span>m<span style="color: #000080;">&gt;</span>
requires InputIterator<span style="color: #000080;">&lt;</span>Iter, U<span style="color: #000080;">&gt;</span>
m<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> foldM<span style="color: #008000;">&#40;</span>Iter begin, Iter end, T i, function<span style="color: #000080;">&lt;</span>m<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>T, U<span style="color: #008000;">&#41;</span><span style="color: #000080;">&gt;</span> f<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>begin <span style="color: #000080;">==</span> end<span style="color: #008000;">&#41;</span>
        <span style="color: #0000ff;">return</span> mreturn<span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">else</span>
        <span style="color: #0000ff;">return</span> mbind<span style="color: #008000;">&#40;</span>f<span style="color: #008000;">&#40;</span>i, <span style="color: #000040;">*</span>begin<span style="color: #008000;">&#41;</span>, <span style="color: #008000;">&#91;</span><span style="color: #000080;">=</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#40;</span>T result<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span>
            Iter next <span style="color: #000080;">=</span> begin<span style="color: #008080;">;</span>
            <span style="color: #000040;">++</span>next<span style="color: #008080;">;</span>
            <span style="color: #0000ff;">return</span> foldM<span style="color: #008000;">&#40;</span>next, end, result, f<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Have template template concepts been covered thoroughly somewhere, and I&#8217;ve just missed it?</p>
<ul style="list-style-type: none;">
<li>[1] &#8220;<a href="(http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.78.2151)">C++ templates/traits versus Haskell typeclasses</a>&#8221; (2005), by Sunil Kothari, Martin Sulzmann.</li>
<li>[2] &#8220;<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2617.pdf">Proposed Wording for Concepts (Revision 5)</a>&#8221; (2008).</li>
<li>[3] &#8220;<a href="http://herbsutter.com/2009/07/21/trip-report/">Trip Report: Exit Concepts, Final ISO C++ Draft in ~18 Months</a>&#8221; (2009), Herb Sutter.</li>
<li>[4] &#8220;ConceptClang: An Implementation of C++ Concepts in Clang&#8221; [<a href="http://www.generic-programming.org/software/ConceptClang/papers/wgp06v-voufo.pdf">pdf</a>]</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/concepts-typeclasses-for-cpp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The case of the different shifts</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/the-case-of-the-different-shifts/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/the-case-of-the-different-shifts/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 18:05:53 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[trivia]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=309</guid>
		<description><![CDATA[Larry Osterman has commented on an interesting edge case in the C/C++ standards, involving the underflow of the right shift operator. They reported that if they compiled code which calculated: 1130149156 &#62;&#62; -05701653 it generated different results on 32bit and &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/the-case-of-the-different-shifts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Larry Osterman has commented on an interesting edge case in the C/C++ standards, involving the underflow of the right shift operator.</p>
<blockquote><p>They reported that if they compiled code which calculated: 1130149156 &gt;&gt; -05701653 it generated different results on 32bit and 64bit operating systems.  On 32bit machines it reported 0 but on 64bit machines, it reported 0x21a.</p></blockquote>
<p>This is one of various areas of &#8220;undefined behavior&#8221; for which you can ask 2 engineers what it should do and get 3 answers, at least one being that &#8220;but I know there must be one!&#8221; I think I know where at least 2 of the answers are coming from &#8230;<span id="more-309"></span><strong> </strong></p>
<p><strong>The Hardware shift</strong></p>
<p>On x64, Larry mentions that the <a href="http://en.wikibooks.org/wiki/X86_Assembly/Shift_and_Rotate">sar instruction</a> is used to carry out the operations. This instruction is not new to the x86 architecture, and in that architecture line&#8217;s early days you did <em>not</em> waste die space. So what&#8217;s cheap?</p>
<p>Enter the <a href="http://en.wikipedia.org/wiki/Barrel_shifter">barrel shifter</a>. It&#8217;s cheap, it&#8217;s small, you pick the maximum power-of-2 shift you want, and that&#8217;s what you pay for. For a 16-bit shift, you can support shifts of 0 to 15 and pay for 4 stages. If you want to shift out all 16, you might think &#8220;add another stage&#8221; &#8212; but it gets worse! It only takes rotation as input. If you need to identify greater shifts than 31, then you&#8217;re toast.</p>
<p>No, what you consider doing is detect shifts &gt; 15, and add a an extra stage to mask away the entire output. But wait, <a href="http://en.wikipedia.org/wiki/Intel_8086">it&#8217;s 1972</a>, and you don&#8217;t have either the die space nor the extra cycles to waste on a conditional masking stage (masking to 4 bits of shift input is free &#8212; you just don&#8217;t connect the other 12 input bits to anything). You just tell the programmer to never shift too much, use the bottom most bits, and ignore the rest. (1 &gt;&gt; 128) == 1.</p>
<p>In time the processor is expanded to support 32-bit quantities and 64-bit quantities, but each time you need to remain compatible, so the sar instruction continues to mask away the upper bits.</p>
<p><strong>The Programming Language</strong></p>
<p>I&#8217;m gonna gloss over the whole &#8220;<a href="http://en.wikipedia.org/wiki/Undefined_behavior">undefined behavior</a>&#8221; thing. Enough <a href="http://blog.regehr.org/archives/213">others</a> have discussed it. Even languages or implementations which aim to minimize it will occasionally miss edge cases or <a href="http://web.mit.edu/~axch/www/scheme/choices/r5rs-letrec.html">fall short</a>.</p>
<p>And C takes a very brutal route of making a great many things &#8220;undefined behavior&#8221; in the name of permitting performance shortcuts. For instance, signed arithmetic overflow yields undefined behavior. This might seem strange now, but at the time 2&#8242;s compliment arithmetic was not common. Choosing 2&#8242;s compliment wrap-around would have introduced perf penalties on 1&#8242;s compliment architectures as they did not generally include native 2&#8242;s compliment instructions, and vice-versa. A modern spin on this are special purpose DSP chips that default to saturating arithmetic.</p>
<p>In any case, I imagine a similar case stands for shifting. One architecture may prefer precise shifting, but x86 prefers to take shifts in modulo. Rather than specify one behavior and penalize compilation on all other hardware, the C language says instead &#8220;this area off limits &#8212; if you want a particular slow-but-precise behavior, implement it yourself&#8221;</p>
<p><strong>The Software Shift</strong></p>
<p>The 32-bit x86 CRT routine mentioned was _allshr (the extra leading underscore comes from <a href="http://blogs.msdn.com/b/oldnewthing/archive/2004/01/08/48616.aspx">cdecl calling convention</a> on x86), and you can find its source in your Visual C++ product installation, under %programfiles%/Microsoft Visual Studio 10.0/vc/crt/src/intel/llshr.asm. It leads off:</p>
<p><!--StartFragment--></p>
<div>
<pre>;
; Handle shifts of 64 bits or more (if shifting 64 bits or more, the result
; depends only on the high order bit of edx).
;
        cmp     cl,64
        jae     short RETSIGN</pre>
</div>
<p><!--EndFragment-->Interesting &#8212; for large shifts, it bails early. Following it is another branch, switching between different implementations for 0-31 and 32-63 bit. In any case, the resulting 3 code paths are short, with the cl &gt;= 64 path being the shortest of all.</p>
<p>Now, the designer could have considered masking instead of comparing &#8212; but for random shift amounts, that would have been a <em>longer</em> code sequence to execute*. And by most reasonable interpretations, returning the sign bit <em>is</em> the right answer.</p>
<p><strong>So there you have it</strong></p>
<p>Each implementation is most efficient and reasonable, when and where it was designed, and both are permitted by a language standard that valued efficiency above most else. And in that respect, both implementations were perfect &#8230; at least, they were when originally written.</p>
<p>* yes, the conditional branch is probably a bigger cost than the savings&#8230; today. While I don&#8217;t know when this code was written, it mentions PROC NEAR, leading me to think that perhaps it comes from a time before <a href="http://en.wikipedia.org/wiki/Superscalar">superscalar architectures</a>, where branches were cheap(er) and arithmetic was costly. You might be want to change it now, but that decision opens up <a href="http://en.wikipedia.org/wiki/Backwards_compatibility">back-compat</a> questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/the-case-of-the-different-shifts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comma Abuse</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/comma-abuse/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/comma-abuse/#comments</comments>
		<pubDate>Wed, 05 May 2010 04:09:53 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=133</guid>
		<description><![CDATA[Found this old C++ source file in my scratch directory, apparently from last September. I don&#8217;t even remember writing this, but it&#8217;s written using my idioms. If I did write it, rest assured it was primarily for amusement purposes (abusement purposes?) only. &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/comma-abuse/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Found this old C++ source file in my scratch directory, apparently from last September. I don&#8217;t even remember writing this, but it&#8217;s written using my idioms. If I did write it, rest assured it was primarily for amusement purposes (abusement purposes?) only.</p>
<p><!--StartFragment--></p>
<blockquote>
<pre>#include &lt;iostream&gt;
using namespace std;

int fibonacci(int x) {
    int a=0, b=1, temp;
    while(x?(--x,temp=a,a=b,b=temp+b):0);
    return a;
}

int main() {
    int i = 0;
    while(i&lt;10&amp;&amp;(cout&lt;&lt;"fib("&lt;&lt;i&lt;&lt;")="&lt;&lt;fibonacci(i)&lt;&lt;'n',++i));
}</pre>
</blockquote>
<p><!--EndFragment--></p>
<p>Yeah. That was terrible. Terrible <em>awesome</em>. But looking back, I&#8217;m realizing that some of the comma abuse is superfluous:</p>
<blockquote>
<pre>int fibonacci(int x){
    int a=0, b=1;
    while(x?(--x,<span style="background-color:#ffff00">a=((b=a+b)-a)</span>):0);
    return a;
}</pre>
</blockquote>
<p>Don&#8217;t let anyone check in code like this, <em>ever</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/comma-abuse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Native Client at UWCS lecture</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/native-client-at-uwcs-lecture/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/native-client-at-uwcs-lecture/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 18:34:17 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[tech talk]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=99</guid>
		<description><![CDATA[Available for streaming and download, Google Native Client presented at UW&#8217;s computer science lecture series. Covers the restrictions on x86 code, new alignment rules, and performance on various benchmarks. 5% overhead, that&#8217;s nothing compared to many other sandboxing techniques. Native &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/native-client-at-uwcs-lecture/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Available for streaming and download, <a href="http://www.uwtv.org/programs/displayevent.aspx?rID=30361&amp;fID=6021">Google Native Client presented</a> at UW&#8217;s computer science lecture series.  Covers the restrictions on x86 code, new alignment rules, and performance on various benchmarks.  5% overhead, that&#8217;s nothing compared to many other sandboxing techniques.</p>
<p>Native client is 50KB download?  Wild. It really is just a gatekeeper, runtime library separate.</p>
<p>Of course, I would love to get away from x86.  LLVM, or ARM, or even Amd64.  x86 makes me a sad panda.</p>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/native-client-at-uwcs-lecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Return-code vs. Exception handling</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/return-code-vs-exception-handling/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/return-code-vs-exception-handling/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 06:21:34 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=59</guid>
		<description><![CDATA[(Originally authored Feb 2008.  This is a revision of an older post from before I began blogging on the internet at large.  It’s been edited for style, not content) This is one of those “religous wars” in programming language theory; &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/return-code-vs-exception-handling/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>(Originally authored Feb 2008.  This is a revision of an older post from before I began blogging on the internet at large.  It’s been edited for style, not content)</em></p>
<p>This is one of those “religous wars” in programming language theory; return code handling (RCH) vs exception handling (EH).  Firstly, I am biased.  Secondly, I will try to remain objective as well, partitioning observations of code using these mechanism from how I feel this reflects on the utility of either mechanism.  I tend to _prefer_ EH in general, but not universally, and generally follow the viewpoint that “exceptions are for exceptional things”.  With that aside…</p>
<p><a href="http://blogs.msdn.com/oldnewthing/">Raymond Chen</a> wrote an article a while back on <a href="http://blogs.msdn.com/oldnewthing/archive/2005/01/14/352949.aspx">RCH vs EH</a><sup>[2]</sup>. There, he points out accurately some facts about code review of RCH and EH, concluding that it’s generally harder to conclude the failure-safety of some example the RCH code than some comparable EH code.</p>
<p>He’s right.  And he’s wrong.  His article is incomplete.  Lets start with defining the playing field.</p>
<p><span id="more-59"></span></p>
<h4>Return Code Handling</h4>
<p>Below, we have two versions of RCH-style code. All failures are communicated via return code. The left version is an erronous example, the failure paths have not yet been considered. The right version has corrected this fault.</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>BOOL </span><span style="font-style: italic; color: #ce6200">ComputeChecksum</span><span>(LPCTSTR pszFile, DWORD</span><span>*</span><span> pdwResult)</span>
<span style="color: #c40000">{</span>
<span>    HANDLE h </span><span>=</span><span> INVALID_HANDLE</span><span>;</span><span> </span>
<span>    HANDLE hfm </span><span>=</span><span> INVALID_HANDLE</span><span>;</span><span> </span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">void</span><span> </span><span>*</span><span>pv</span><span>;</span>
<span>    DWORD dwHeaderSum</span><span>;</span>

<span>    h </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">CreateFile</span><span>(...)</span><span>;</span>

<span>    hfm </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">CreateFileMapping</span><span>(h, ...)</span><span>;</span>

<span>    pv </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">MapViewOfFile</span><span>(hfm, ...)</span><span>;</span>

<span>    </span><span style="font-style: italic; color: #ce6200">CheckSumMappedFile</span><span>(... </span><span>&amp;</span><span>dwHeaderSum, pdwResult)</span><span>;</span>

<span>    </span><span style="font-style: italic; color: #ce6200">UnmapViewOfFile</span><span>(pv)</span><span>;</span>
<span>    </span><span style="font-style: italic; color: #ce6200">CloseHandle</span><span>(hfm)</span><span>;</span>
<span>    </span><span style="font-style: italic; color: #ce6200">CloseHandle</span><span>(h)</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> TRUE</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</div>
</td>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>BOOL </span><span style="font-style: italic; color: #ce6200">ComputeChecksum</span><span>(LPCTSTR pszFile, DWORD</span><span>*</span><span> pdwResult)</span>
<span style="color: #c40000">{</span>
<span>    HANDLE h </span><span>=</span><span> INVALID_HANDLE</span><span>;</span><span> </span>
<span>    HANDLE hfm </span><span>=</span><span> INVALID_HANDLE</span><span>;</span><span> </span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">void</span><span> </span><span>*</span><span>pv </span><span>=</span><span> </span><span style="color: #c04000; font-weight: bolder">NULL</span><span>;</span><span> </span>
<span>    DWORD dwHeaderSum</span><span>;</span>
<span>    BOOL result </span><span>=</span><span> FALSE</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( (h </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">CreateFile</span><span>(...)) </span><span>==</span><span> INVALID_HANDLE)</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">goto</span><span> cleanup</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( (hfm </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">CreateFileMapping</span><span>(h, ...) </span>
<span>          </span><span>==</span><span> INVALID_HANDLE ) )</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">goto</span><span> cleanup</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( (pv </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">MapViewOfFile</span><span>(hfm, ...)) </span><span>==</span><span> </span><span style="color: #c04000; font-weight: bolder">NULL</span><span> )</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">goto</span><span> cleanup</span><span>;</span>

<span>    </span><span style="font-style: italic; color: #ce6200">CheckSumMappedFile</span><span>(... </span><span>&amp;</span><span>dwHeaderSum, pdwResult)</span><span>;</span>
<span>    result </span><span>=</span><span> TRUE</span><span>;</span>

<span>    cleanup</span><span>:</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> (pv) </span><span style="font-style: italic; color: #ce6200">UnmapViewOfFile</span><span>(pv)</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> (hfm </span><span>!=</span><span> INVALID_HANDLE) </span><span style="font-style: italic; color: #ce6200">CloseHandle</span><span>(hfm)</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> (h </span><span>!=</span><span> INVALID_HANDLE) </span><span style="font-style: italic; color: #ce6200">CloseHandle</span><span>(h)</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> result</span><span>;</span>
<span style="color: #c40000">}</span><span>   </span></pre>
</div>
</td>
</tr>
</tbody>
</table>
<p>The left side looks very clean, and very clearly does <em>no</em> RCH, so according to Chen’s method it is clearly incorrect. According to [2], the left one is ‘Really Easy’ to write, and ‘Really Easy’ to recognize as being incorrect. The lack of an if-statement <strong>every 2 lines </strong>is a red flag. Basically, you must explicitly write every possible success and failure code path, even the “uninteresting” ones.</p>
<p>Let’s move on to the EH example from Chen’s post.</p>
<h4>Exception Handling (old style)</h4>
<p>Bellow is adaptation of both the incorrect EH code from his article, along with a possible fix.</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>NotifyIcon</span><span>*</span><span> </span><span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>()</span>
<span style="color: #c40000">{</span>
<span>    NotifyIcon</span><span>*</span><span> icon</span><span>;</span><span> </span>

<span>    icon </span><span>=</span><span> </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>()</span><span>;</span>

<span>    icon.</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>
<span>    icon.</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(</span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...), </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>())</span><span>;</span>
<span>    icon.</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> icon</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</td>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>NotifyIcon</span><span>*</span><span> </span><span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>()</span>
<span style="color: #c40000">{</span>
<span>    NotifyIcon</span><span>*</span><span> icon </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>

<span>    icon </span><span>=</span><span> </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>()</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">try</span><span> </span><span style="color: #c40000">{</span>
<span>        icon.</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>
<span>        icon.</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>
<span>        Info info </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>()</span><span>;</span>
<span>        icon.</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(</span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...), info)</span><span>;</span>
<span>    </span><span style="color: #c40000">}</span><span> </span><span style="color: #0000ff; font-weight: bolder">catch</span><span> (...) </span><span style="color: #c40000">{</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">delete</span><span> icon</span><span>;</span><span> </span><span style="color: #0000ff; font-weight: bolder">throw</span><span>;</span>
<span>    </span><span style="color: #c40000">}</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> icon</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</td>
</tr>
</tbody>
</table>
<p>I totally agree with any and all critics that the above style of code is tough to diagnose. If any of { set_text, set_icon, set_visible, or get_info } can throw, the left code is totally busted. The code to the right is tricky… by moving GetInfo to a separate line, and set_icon to the end, the Icon object can’t be leaked (presumably set_icon is responsible for freeing the Icon in failure conditions). The try-catch will delete NotifyIcon and propogate the exception, but not without having made this program a pain to debug – we will see two exception raise events now instead of just one.</p>
<p>Even worse, tomorrow this code could become incorrect again – if the copy-constructor for Info can throw, the right side code is <em>still</em> wrong. I bet you didn’t think of that. Think you’re an expert at this? Try item #18 in Exceptional C++<sup>[3]</sup>. I think my first time I found about 16 code paths in the 3 lines of C++ code, barely teetering into ‘Guru’ category, but I spent like 15 minutes on it. Normally you have 5 seconds during a code review, and you won’t find all 23 code paths in 5 seconds. You have to do better than analyzing ever code path.</p>
<p>Applying Raymon Chen’s categories, getting to the correct code is “Really Hard”, and I hope the audience agrees with me. It is hard. Any line of code, any subexpression could throw, and we have to look at all those possible cases. RCH certainly looks better. Sure, we’d have to have like 9 ‘if’ statements to bring the above code in line, but at least then we could see that we covered all the code paths. But there is no general rule we can apply to see if it is trivially incorrect. In RCH, a line without a conditional branch is suspect. In EH (old style), a line without a try-catch after resource acquisition is suspect.</p>
<p>I call this <strong>‘old style’</strong> because it looks a lot like how you’d handle exceptions in C#, or in C++ without any library support back in 1990. Stephan T. Lavavej makes a distinction between “archaic C++” and “modern C++”<sup>[4]</sup>. And Raymond Chen notes in parting words, “Yes, there are programming models like RAII and transactions, but rarely do you see sample code that uses either.” – let’s remedy this situation.</p>
<h4>Exception Handling (modern)</h4>
<p>On the left, we have some bad RAII exception handling code, to parallel Chen’s original bad example. On the right, the ‘fixed’ version.</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>shared_ptr</span><span>&lt;</span><span>NotifyIcon</span><span>&gt;</span>
<span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>()</span>
<span style="color: #c40000">{</span>
<span>    NotifyIcon</span><span>*</span>
<span>      </span><span style="font-style: italic; color: #ce6200">icon</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>() )</span><span>;</span>

<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>

<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(</span>
<span>        shared_ptr</span><span>&lt;</span><span>Icon</span><span>&gt;</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...) ),</span>
<span>        </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>())</span><span>;</span>

<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> icon</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</td>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>shared_ptr</span><span>&lt;</span><span>NotifyIcon</span><span>&gt;</span>
<span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>()</span>
<span style="color: #c40000">{</span>
<span>    shared_ptr</span><span>&lt;</span><span>NotifyIcon</span><span>&gt;</span><span> </span>
<span>        </span><span style="font-style: italic; color: #ce6200">icon</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>() )</span><span>;</span>

<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>

<span>    shared_ptr</span><span>&lt;</span><span>Icon</span><span>&gt;</span><span> </span>
<span>        </span><span style="font-style: italic; color: #ce6200">inner</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...) )</span><span>;</span>
<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(inner, </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>())</span><span>;</span>

<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> icon</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</td>
</tr>
</tbody>
</table>
<p>I’m changing the rules. I don’t care how many branches there are, success or failure branches. What I <strong><em>do </em></strong>care about is that, at every point of time, there is exactly one owner for ever resource, and that in a general failure condition, that owner will take care of the resource.</p>
<p>That is the fundamental change. Modern C++ code <strong>using RAII does not generally have any explicit code for failure conditions</strong>. General failures are always handled non-locally. Local resource management is <strong>immediately</strong> handled by automatic objects, using RAII. Any raw resources (such as allocating a new object) must immediately be handed off to an RAII object.</p>
<p>Lets take a closer look at what I find wrong with the left example.</p>
<ul>
<li>First line, we have a raw pointer. Bad. RAII rule: raw pointers == suspect code.</li>
<li>Second line, set_text. No raw resources. Good.</li>
<li>Third line, shared_ptr is mixed in with another call. Bad. Move to a separate line.</li>
<li>Last line, set_visible, also good.</li>
</ul>
<p>How do we know we are done? When there are only two kinds of statements – RAII object initialization, and useful code that doesn’t create unadorned resources. Now, it is admittedly hard to get some RAII classes right in the first place, but that only needs to be done once per class, instead of once per use.</p>
<p>While it is still hard to see all the code paths, it becomes really <strong>easy </strong>to check if the developer has finished EH. Any resource allocation without RAII will tell you that the developer didn’t finish. Sure, bad RCH code pops out like a rose in a weed garden, but with RAII you can usually skip writing the bad code in the first place – just jump directly to shared_ptr&lt;T&gt;, or shared_factory&lt;HANDLE, close_handle&gt;::type, or scope_guard&lt;T&gt;, etc. You can skip writing the bad code at all, and do all your failure handling via RAII.</p>
<h4>Final Thoughts</h4>
<p>So, we have a new table for recognizing code:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="215" valign="top"><em>Difference between good and bad RCH code</em></td>
<td width="423" valign="top">· Is there an ‘if’ statement for every function call that could fail?</p>
<p>· Is there a cleanup block and goto?</p>
<p>· Is every resource mentioned in the cleanup block?</td>
</tr>
<tr>
<td width="215" valign="top"><em>Difference between good and bad EH (old style) code</em></td>
<td width="423" valign="top">· Which statements / sub-expressions can throw? Number of potentially throws == number of ‘if’ statements possible in RCH style code.</p>
<p>· Is there a catch-rethrow block for every resource that needs cleanup?</p>
<p>· Make sure there are no ‘goto’ statements – they break C++ destructors</td>
</tr>
<tr>
<td width="215" valign="top"><em>Difference between good and bad EH (modern) code</em></td>
<td width="423" valign="top">· Are native resources immediately stored in RAII objects?</p>
<p>· Is RAII initialization on a separate line.</p>
<p>· Suspect any usage of delete, or usages of array new (prefer vector to array-new).</td>
</tr>
</tbody>
</table>
<p>And here’s how I believe modern EH with RAII fits in Raymond Chen’s table.</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="215" valign="top">Recognition Task</td>
<td width="78" valign="top">Easy</td>
<td width="78" valign="top">Hard</td>
<td width="90" valign="top">Really Hard</td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #808040;">is RCH code bad</span></td>
<td width="78" valign="top"><span style="color: #808040;">X</span></td>
<td width="78" valign="top"><span style="color: #808040;"> </span></td>
<td width="90" valign="top"><span style="color: #808040;"> </span></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #808040;">diff between bad &amp; not-bad</span></td>
<td width="78" valign="top"><span style="color: #808040;">X</span></td>
<td width="78" valign="top"><span style="color: #808040;"> </span></td>
<td width="90" valign="top"><span style="color: #808040;"> </span></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #808040;">is RCH code not-bad</span></td>
<td width="78" valign="top"><span style="color: #808040;"> </span></td>
<td width="78" valign="top"><span style="color: #808040;">X</span></td>
<td width="90" valign="top"></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #ff0000;">is EH (os) code bad</span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="90" valign="top"><span style="color: #ff0000;">X</span></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #ff0000;">diff between bad &amp; not-bad</span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="90" valign="top"><span style="color: #ff0000;">X</span></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #ff0000;">is EH (os) code not-bad</span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="78" valign="top"><span style="color: #ff0000;"> </span></td>
<td width="90" valign="top"><span style="color: #ff0000;">X</span></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #008040;">is EH (m) code bad</span></td>
<td width="78" valign="top"><span style="color: #008040;"> </span></td>
<td width="78" valign="top"><span style="color: #008040;">X</span></td>
<td width="90" valign="top"></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #008040;">diff between bad &amp; not-bad</span></td>
<td width="78" valign="top"><span style="color: #008040;">X</span></td>
<td width="78" valign="top"></td>
<td width="90" valign="top"></td>
</tr>
<tr>
<td width="215" valign="top"><span style="color: #008040;">is EH (m) code not-bad</span></td>
<td width="78" valign="top"><span style="color: #008040;">X</span></td>
<td width="78" valign="top"></td>
<td width="90" valign="top"></td>
</tr>
</tbody>
</table>
<p>Finally, I’ll leave you with my interpretation of RCH vs. EH (modern).</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top"><em>Correct RCH-style</em></td>
<td width="200" valign="top"><em>Correct-EH(modern)-style</em></td>
</tr>
<tr>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>HRESULT</span>
<span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>(NotifyIcon</span><span>**</span><span> ppResult)</span>
<span style="color: #c40000">{</span>
<span>    NotifyIcon</span><span>*</span><span>      icon </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>
<span>    Icon</span><span>*</span><span>            inner </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">const</span><span> </span><span style="color: #0000ff; font-weight: bolder">wchar_t</span><span> </span><span>*</span><span>  tmp1 </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>
<span>    HRESULT          hr </span><span>=</span><span> S_OK</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) ) </span><span style="color: #c40000">{</span>
<span>        icon </span><span>=</span><span> </span><span style="color: #0000ff; font-weight: bolder">new</span><span> (nothrow) </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>()</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span>!</span><span>icon ) hr </span><span>=</span><span> E_OUTOFMEM</span><span>;</span>
<span>    </span><span style="color: #c40000">}</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) )</span>
<span>        hr </span><span>=</span><span> icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) ) </span><span style="color: #c40000">{</span>
<span>        inner </span><span>=</span><span> </span><span style="color: #0000ff; font-weight: bolder">new</span><span> (nothrow) </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...)</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span>!</span><span>inner )</span>
<span>            hr </span><span>=</span><span> E_OUTOFMEM</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">else</span><span> </span><span style="color: #c40000">{</span>
<span>            Info info</span><span>;</span>
<span>            hr </span><span>=</span><span> </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>( </span><span>&amp;</span><span>info )</span><span>;</span>

<span>            </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) )</span>
<span>                hr </span><span>=</span><span> icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(inner, info)</span><span>;</span>
<span>            </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) )</span>
<span>                inner </span><span>=</span><span> </span><span style="color: #c04000; font-weight: bolder">NULL</span><span>;</span>
<span>        </span><span style="color: #c40000">}</span>
<span>    </span><span style="color: #c40000">}</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) )</span>
<span>        hr </span><span>=</span><span> icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( </span><span style="font-style: italic; color: #ce6200">SUCCEEDED</span><span>(hr) ) </span><span style="color: #c40000">{</span>
<span>        </span><span>*</span><span>ppResult </span><span>=</span><span> icon</span><span>;</span>
<span>        icon </span><span>=</span><span> </span><span style="color: #c04000; font-weight: bolder">NULL</span><span>;</span>
<span>    </span><span style="color: #c40000">}</span><span> </span><span style="color: #0000ff; font-weight: bolder">else</span><span> </span><span style="color: #c40000">{</span>
<span>        </span><span>*</span><span>ppResult </span><span>=</span><span> </span><span style="color: #c04000; font-weight: bolder">NULL</span><span>;</span>
<span>    </span><span style="color: #c40000">}</span>

<span>    cleanup</span><span>:</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( inner ) </span><span style="color: #0000ff; font-weight: bolder">delete</span><span> inner</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">if</span><span> ( icon ) </span><span style="color: #0000ff; font-weight: bolder">delete</span><span> icon</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> hr</span><span>;</span><span> </span>
<span style="color: #c40000">}</span></pre>
</div>
</td>
<td width="200" valign="top">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<div style="background-color: #ffffff; font-style: normal; font-family: &quot;Bitstream Vera Sans Mono&quot;; color: #000000; font-size: 8pt; font-weight: normal; text-decoration: none">
<pre style="font-size: 8pt"><span>shared_ptr</span><span>&lt;</span><span>NotifyIcon</span><span>&gt;</span>
<span style="font-style: italic; color: #ce6200">CreateNotifyIcon</span><span>()</span>
<span style="color: #c40000">{</span>
<span>    shared_ptr</span><span>&lt;</span><span>NotifyIcon</span><span>&gt;</span><span> icon</span><span>;</span><span style="font-style: italic; color: #008000">//[5]</span>
<span>    shared_ptr</span><span>&lt;</span><span>Icon</span><span>&gt;</span><span>       inner</span><span>;</span>

<span>    icon.</span><span style="font-style: italic; color: #ce6200">reset</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">NotifyIcon</span><span>() )</span><span>;</span>
<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_text</span><span>(</span><span style="color: #008080">"Blah blah blah"</span><span>)</span><span>;</span>

<span>    inner.</span><span style="font-style: italic; color: #ce6200">reset</span><span>( </span><span style="color: #0000ff; font-weight: bolder">new</span><span> </span><span style="font-style: italic; color: #ce6200">Icon</span><span>(...) )</span><span>;</span>
<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_icon</span><span>(inner, </span><span style="font-style: italic; color: #ce6200">GetInfo</span><span>())</span><span>;</span>
<span>    icon</span><span>-&gt;</span><span style="font-style: italic; color: #ce6200">set_visible</span><span>(</span><span style="color: #0000ff; font-weight: bolder">true</span><span>)</span><span>;</span>

<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> icon</span><span>;</span>
<span style="color: #c40000">}</span></pre>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<p>Footnotes:</p>
<p>1 – C++ FAQ Lite, Section 17 “Exceptions and error handling” <a href="http://www.parashift.com/c++-faq-lite/exceptions.html">http://www.parashift.com/c++-faq-lite/exceptions.html</a></p>
<p>2 – Raymond Chen, “Cleaner, more elegant, and harder to recognize” <a href="http://blogs.msdn.com/oldnewthing/archive/2005/01/14/352949.aspx">http://blogs.msdn.com/oldnewthing/archive/2005/01/14/352949.aspx</a></p>
<p>3 – Herb Sutter, “Exceptional C++”, <a href="http://www.amazon.com/Exceptional-C%2B%2B-Engineering-Programming-Depth/dp/0201615622/">http://www.amazon.com/Exceptional-C%2B%2B-Engineering-Programming-Depth/dp/0201615622/</a></p>
<p>4 – Stephan T. Lavavej, aka STL, “Modern C++” <a href="http://nuwen.net/14882.html">http://nuwen.net/14882.html</a></p>
<p>5 – some may note that auto_ptr (or unique_ptr in C++0x) may provide better efficiency, and safely auto-converts to shared_ptr. That is another alternative.  Just don’t use raw ptrs and make sure to review Effective C++ on auto_ptr safety.</p>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/return-code-vs-exception-handling/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Memoizer, in C++</title>
		<link>http://ra3s.com/wordpress/dysfunctional-programming/memoizer-in-c/</link>
		<comments>http://ra3s.com/wordpress/dysfunctional-programming/memoizer-in-c/#comments</comments>
		<pubDate>Sun, 16 Nov 2008 10:36:25 +0000</pubDate>
		<dc:creator>aaron</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://ra3s.com/wordpress/dysfunctional-programming/?p=8</guid>
		<description><![CDATA[Part of what I&#8217;m trying to do here is record experiments, little bits of code demonstrating software techniques.&#160; This is a revisit of a recent one. As a refresher, memoization is a dynamic programming technique used to optimize the time &#8230; <a href="http://ra3s.com/wordpress/dysfunctional-programming/memoizer-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Part of what I&#8217;m trying to do here is record experiments, little bits of code demonstrating software techniques.&#160; This is a revisit of a recent one.</p>
<p>As a refresher, <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> is a dynamic programming technique used to optimize the time to solve problems where partial problems overlap frequently.&#160; For example, in the recursive definition of the <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci sequence</a>, F(x) = { 1 : x &lt; 2,&#160; F(x-1)+F(x-2) : x&gt;=2 }, at each stage, you compute the solution by taking the results from two separate computations.</p>
<p>So, walking briefly through, get the C++ bootstrapping out of the way.&#160; To start, we include the standard module&#8217;s we&#8217;ll be using:</p>
<blockquote><pre><span style="color: #808000; font-weight: bolder">#include</span><span> </span><span style="color: #800000">&lt;</span><span>iostream</span><span style="color: #800000">&gt;</span>
<span style="color: #808000; font-weight: bolder">#include</span><span> </span><span style="color: #800000">&lt;</span><span>iomanip</span><span style="color: #800000">&gt;</span>
<span style="color: #808000; font-weight: bolder">#include</span><span> </span><span style="color: #800000">&lt;</span><span>map</span><span style="color: #800000">&gt;</span></pre>
</blockquote>
<p>Next up, the memoizer &#8212; this is a helper class that will record the results for us.&#160; </p>
<blockquote>
<div style="background-color: #ffffff; font-style: normal; font-family: " none?="none?" TEXT-DECORATION:="TEXT-DECORATION:" normal;="normal;" FONT-WEIGHT:="FONT-WEIGHT:" 10pt;="10pt;" FONT-SIZE:="FONT-SIZE:" #000000;="#000000;" COLOR:="COLOR:" new?;="new?;" courier="courier">
<pre><span style="color: #0000ff; font-weight: bolder">template</span><span> </span><span>&lt;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">class</span><span> Result, </span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">class</span><span> Arg,</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">class</span><span> ResultStore </span><span>=</span><span> </span><span style="color: #c04000; font-weight: bolder">std</span><span>::</span><span style="color: #c04000; font-weight: bolder">map</span><span>&lt;</span><span>Arg, Result</span><span>&gt;</span>
<span>&gt;</span>
<span style="color: #0000ff; font-weight: bolder">class</span><span> memoizer1</span><span style="color: #800000">{</span>
<span style="color: #0000ff; font-weight: bolder">public</span><span>:</span>
<span>    </span><span style="font-style: italic; color: #008000">// accelerate 'f' by remembering partial results</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">template</span><span> </span><span>&lt;</span><span style="color: #0000ff; font-weight: bolder">class</span><span> F</span><span>&gt;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">const</span><span> Result</span><span>&amp;</span><span> </span><span style="color: #0000ff; font-weight: bolder">operator</span><span>()(F f, </span><span style="color: #0000ff; font-weight: bolder">const</span><span> Arg</span><span>&amp;</span><span> a)</span><span style="color: #800000">{</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">typename</span><span> ResultStore</span><span>::</span><span style="color: #c04000; font-weight: bolder">const_iterator</span><span> it </span><span>=</span><span> memo_.</span><span style="color: #c04000; font-weight: bolder">find</span><span>(a)</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">if</span><span>(it </span><span>==</span><span> memo_.</span><span style="font-weight: bolder">end</span><span>()) </span><span style="color: #800000">{</span>
<span>            it </span><span>=</span><span> memo_.</span><span style="font-weight: bolder">insert</span><span>(</span><span style="color: #c04000; font-weight: bolder">make_pair</span><span>(a, </span><span style="font-weight: bolder">f</span><span>(a))).first</span><span>;</span>
<span>        </span><span style="color: #800000">}</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">return</span><span> it</span><span>-&gt;</span><span>second</span><span>;</span>
<span>    </span><span style="color: #800000">}</span>
<span style="color: #0000ff; font-weight: bolder">private</span><span>:</span>
<span>    ResultStore memo_</span><span>;</span>
<span style="color: #800000">}</span><span>;</span></pre>
</p></div>
</blockquote>
<p>We&#8217;ll separate the definition of fibonacci function from the public surface so that the memoizer can be applied later</p>
<blockquote>
<div style="background-color: #ffffff; font-style: normal; font-family: " none?="none?" TEXT-DECORATION:="TEXT-DECORATION:" normal;="normal;" FONT-WEIGHT:="FONT-WEIGHT:" 10pt;="10pt;" FONT-SIZE:="FONT-SIZE:" #000000;="#000000;" COLOR:="COLOR:" new?;="new?;" courier="courier">
<pre><span style="color: #0000ff; font-weight: bolder">int</span><span> </span><span style="font-weight: bolder">fib</span><span>(</span><span style="color: #0000ff; font-weight: bolder">int</span><span>)</span><span>;</span>

<span style="color: #0000ff; font-weight: bolder">namespace</span><span> </span><span style="color: #800000">{</span>
<span>    </span><span style="font-style: italic; color: #008000">// instrumentation, track number of uses</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">int</span><span> total_ops </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>

<span>    </span><span style="font-style: italic; color: #008000">// implementation</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">int</span><span> </span><span style="font-weight: bolder">fib_</span><span>(</span><span style="color: #0000ff; font-weight: bolder">int</span><span> n)</span><span style="color: #800000">{</span>
<span>        </span><span>++</span><span>total_ops</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">if</span><span>(n </span><span>==</span><span> </span><span style="color: #000080">0</span><span> </span><span>||</span><span> n </span><span>==</span><span> </span><span style="color: #000080">1</span><span>) </span>
<span>            </span><span style="color: #0000ff; font-weight: bolder">return</span><span> </span><span style="color: #000080">1</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">else</span>
<span>            </span><span style="color: #0000ff; font-weight: bolder">return</span><span> </span><span style="font-weight: bolder">fib</span><span>(n</span><span>-</span><span style="color: #000080">1</span><span>) </span><span>+</span><span> </span><span style="font-weight: bolder">fib</span><span>(n</span><span>-</span><span style="color: #000080">2</span><span>)</span><span>;</span>
<span>    </span><span style="color: #800000">}</span>
<span style="color: #800000">}</span></pre>
</p></div>
</blockquote>
<p>Lastly the driver function will decorate the implementation with a memoizer, and a prompt loop.&#160; You should be able to copy-paste the code into a cpp file, comple, then run.</p>
<blockquote>
<div style="background-color: #ffffff; font-style: normal; font-family: " none?="none?" TEXT-DECORATION:="TEXT-DECORATION:" normal;="normal;" FONT-WEIGHT:="FONT-WEIGHT:" 10pt;="10pt;" FONT-SIZE:="FONT-SIZE:" #000000;="#000000;" COLOR:="COLOR:" new?;="new?;" courier="courier">
<pre><span style="font-style: italic; color: #008000">// driver function</span>
<span style="color: #0000ff; font-weight: bolder">int</span><span> </span><span style="font-weight: bolder">fib</span><span>(</span><span style="color: #0000ff; font-weight: bolder">int</span><span> n) </span><span style="color: #800000">{</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">static</span><span> memoizer1</span><span>&lt;</span><span style="color: #0000ff; font-weight: bolder">int</span><span>,</span><span style="color: #0000ff; font-weight: bolder">int</span><span>&gt;</span><span> memo</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">return</span><span> </span><span style="font-weight: bolder">memo</span><span>(fib_, n)</span><span>;</span>
<span style="color: #800000">}</span>

<span style="color: #0000ff; font-weight: bolder">using</span><span> </span><span style="color: #0000ff; font-weight: bolder">namespace</span><span> </span><span style="color: #c04000; font-weight: bolder">std</span><span>;</span>

<span style="color: #0000ff; font-weight: bolder">int</span><span> </span><span style="font-weight: bolder">main</span><span>()</span><span style="color: #800000">{</span>
<span>    </span><span style="color: #c04000; font-weight: bolder">cout</span><span> </span><span>&lt;&lt;</span><span> </span><span style="color: #008080">&quot;fibonacci numbers, memoized, ctrl+z to quitn&quot;</span><span>;</span>
<span>    </span><span style="color: #0000ff; font-weight: bolder">for</span><span>(</span><span>;;</span><span>) </span><span style="color: #800000">{</span>
<span>        </span><span style="color: #c04000; font-weight: bolder">cout</span><span> </span><span>&lt;&lt;</span><span> </span><span style="color: #008080">&quot;enter integer: &quot;</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">int</span><span> x</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">if</span><span>(</span><span>!</span><span>(</span><span style="color: #c04000; font-weight: bolder">cin</span><span> </span><span>&gt;&gt;</span><span> x))</span>
<span>            </span><span style="color: #0000ff; font-weight: bolder">break</span><span>;</span>

<span>        total_ops </span><span>=</span><span> </span><span style="color: #000080">0</span><span>;</span>
<span>        </span><span style="color: #0000ff; font-weight: bolder">int</span><span> y </span><span>=</span><span> </span><span style="font-weight: bolder">fib</span><span>(x)</span><span>;</span>

<span>        </span><span style="color: #c04000; font-weight: bolder">cout</span><span> </span><span>&lt;&lt;</span><span> </span><span style="color: #008080">&quot;fib(&quot;</span><span> </span><span>&lt;&lt;</span><span> x </span><span>&lt;&lt;</span><span> </span><span style="color: #008080">&quot;) == &quot;</span><span> </span><span>&lt;&lt;</span><span> y </span><span>&lt;&lt;</span><span> </span><span style="color: #c04000; font-weight: bolder">endl</span><span>;</span>
<span>        </span><span style="color: #c04000; font-weight: bolder">cout</span><span> </span><span>&lt;&lt;</span><span> </span><span style="color: #008080">&quot;cost was &quot;</span><span> </span><span>&lt;&lt;</span><span> total_ops </span><span>&lt;&lt;</span><span> </span><span style="color: #c04000; font-weight: bolder">endl</span><span>;</span>
<span>    </span><span style="color: #800000">}</span>
<span style="color: #800000">}</span></pre>
</p></div>
</blockquote>
<p>And that&#8217;s the complete program.&#160; Trying it with a few inputs, you&#8217;ll see few number of operations.&#160; To see the non-memoized results, you need only comment out the code for &#8216;fib()&#8217; and have it invoke &#8216;fib_&#8217; directly &#8212; the results will slow to a halt around x=30 to 35.</p>
<p>By using a look up table, each time &#8216;fib&#8217; is invoked with a given value of &#8216;x&#8217;, the result is stored so it doesn&#8217;t need to recurse again.&#160; A hash table, or even a dynamically sizing array (std::vector) could have also been used in this case, but may not be appropriate for other problem spaces.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://ra3s.com/wordpress/dysfunctional-programming/memoizer-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

