    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: â€˜No Bugsâ€™ Top Five C++ Cooking Recipes</title>
        <link>https://members.accu.org/index.php/articles/1874</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #113 - February 2013</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c320/">o113</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-320/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+320/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;â€˜No Bugsâ€™ Top Five C++ Cooking Recipes</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 06 February 2013 20:49:27 +00:00 or Wed, 06 February 2013 20:49:27 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Developers often have a few favourite tricks for solving problems. Sergey Ignatchenko shares his five top recipes.</p>
<p><strong>Body:</strong>&nbsp;<p>Disclaimer: as usual, the opinions within this article are those of â€˜No Bugsâ€™ Bunny, and do not necessarily coincide with the opinions of the translator or the <em>Overload</em> editor. Please also keep in mind that translation difficulties from Lapine (like those described in <a href="#[Loganberry04]">[Loganberry04]</a>) might have prevented providing an exact translation. In addition, both the translator and <em>Overload</em> expressly disclaim all responsibility from any action or inaction resulting from reading this article.</p>

<p>Today, Iâ€™ve decided to recall that Iâ€™m a developer (at least at heart), and pause my usual philosophical blabber about the place of developers in the Universe to talk about actual programming a little bit.</p>

<p>Most (if not all) of the stuff in this article is rather well-known, however, such things are frequently overlooked, so I feel that they are worth mentioning once again.</p>

<h2>Recipe #5 â€“ set&lt;&gt;, sort(), and â€˜strict weak orderingâ€™</h2>

<p>With <code>set</code>s/<code>map</code>s/<code>sort</code>s there is a well-known headache: how to write a compliant <code>operator &lt;()</code> (or a functor). It is known that for classes involved in <code>map&lt;&gt;</code>/<code>set&lt;&gt;</code>, <code>operator &lt;()</code> <em>must</em> comply to a so-called â€˜strict weak orderingâ€™; if this is violated, all kinds of weird things can happen (from identical multiple entries in a supposedly-unique collection, to memory corruption). Unfortunately, looking at an arbitrary <code>operator &lt;()</code>, it is usually rather (or very) difficult to tell if it complies with â€˜strict weak orderingâ€™. Recipe #5 shows how to cook an <code>operator &lt;()</code> which does comply with â€˜strict weak orderingâ€™ and therefore can be safely used with <code>set</code>s/<code>map</code>s (and also with <code>sort</code>s etc.) â€“ see Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class X {
  int i;
  int j;
  string s;
  Y y;
  ZZ zz;

  bool operator &lt;( const X&amp; other ) const {
    if( i != other.i )
      return i &lt; other.i;
    if( s != other.s )
      return s &lt; other.s;
    //it is ok to ignore some fields
    return false;
  }
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p><code>operator &lt;()</code> in Listing 1 is guaranteed to comply with â€˜strict weak orderingâ€™ (assuming that nobody has redefined comparison for <code>string</code>s).</p>

<p>If necessary, class members can also be included into the comparison (provided that their respective <code>operators &lt;()</code> are also compliant with â€˜strict weak orderingâ€™):</p>

<pre class="programlisting">
  bool yl = y &lt; other.y;
  bool yg = other.y &lt; y;
  if( yl || yg ) // this is just a way to write
                 // &quot;y != other.y&quot;
    return yl;</pre>


<p>In addition, functions can also be used (as long as their arguments are constant):</p>

<pre class="programlisting">
int fthis = f( i );
int fother = f( other.i );
if( fthis != fother )
  return fthis &lt; fother;</pre>

<p>Multi-parameter functions are also possible (as long as all arguments are constant, and as long as theyâ€™re used exactly as shown below):</p>

<pre class="programlisting">
  int fthis = f( i, s );
  int fother = f( other.i, other.s );
  if( fthis != fother )
    return fthis &lt; fother;</pre>

<p>It is very important to note that while in any of the above examples, â€˜strict weak orderingâ€™ is guaranteed, any deviations from the forms described above, can be deadly. For example, if you replace <code>return false;</code> with innocent-looking <code>return true;</code>, it would break the code (as for certain <code>a</code> and <code>b</code> our <code>operator &lt;()</code> would return that <code>a &lt; b</code> is true, and simultaneously that <code>a &gt; b</code> is true, which is obviously wrong). In another example, comparing <code>f(i, j)</code> with <code>f(other.j, other.i)</code> would be risky (while comparing <code>f(i, j)</code> with <code>f(other.i, other.j)</code> is guaranteed to be ok under the conditions stated above).</p>

<h2>Recipe #4 â€“ Measuring run-time performance</h2>

<p>In production code, it is often desirable to gather statistics to measure code performance under real conditions. The problem  is how to gather statistics without hurting performance too much. Here are a few tricks to help deal with this issue.</p>

<p>First, for statistical purposes it is usually not necessary to use any kind of thread synchronization. Yes, if youâ€™re writing plain <code>stats.nCalls++</code> without using mutexes or atomics, you might get an error if two threads try to modify the same <code>stats.nCalls</code> simultaneously; however, if all the statements modifying <code>stats.nCalls</code>, are incremental ones (like the one above) the error from a single race condition cannot exceed 1. In addition, the chance of race conditions is very slim (even if you try really hard, getting more than 1/100 of assignments to have race conditions would be difficult, and in practice it is usually more like 1e-4 to 1e-5 or so). We can usually say (given enough calls) that statistical errors due to race conditions are negligible.</p>

<p>Another issue which often arises in relation to measuring run-time performance is time measurement. The problem here is the following: usually the time frames to be measured are very small (often within a microsecond), and high-precision methods available to measure time are not always readily available. (For example, an x86 RDTSC instruction was observed to provide incorrect results on certain multi-socket hardware due to incorrect implementation of the motherboard.) So, what should you do if you need to measure how long certain function takes (in microseconds), but all you have is a very low-precision timer (like a 15-milliseconds timer)? Apparently, if you have lots and lots of calls to your function, it is often ok to take time measurements using a low-precision timer, and simply add them up (using something like <code>stats.callTime += deltaTime;</code>. It might be even better to reduce performance impact, <code>if( __builtin_expect( deltaTime, 0 ) ) stats.callTime += deltaTime;</code> â€“ potentially without synchronization, as described above). If youâ€™re measuring a time interval of 1.5 microseconds, and have a timer which has precision of 15 milliseconds, you will get <code>deltaTime == 0</code> in 99.99% of the cases, but apparently, after averaging a million such calls, results are usually surprisingly precise (the precision Iâ€™ve observed in practice was about Â±20%, which is much better than one would expect intuitively given the numbers above). While precision is not guaranteed and your mileage may vary, if you donâ€™t have any other options on the table â€“ for example, because RDTSC doesnâ€™t work properly on your multi-socket hardware â€“ it is certainly worth a try.</p>

<h2>Recipe #3 â€“ _set_se_translator</h2>

<p>There is only one thing which I think is fundamentally better with the Microsoft Visual C++ compiler than with GCC, and it is the <code>_set_se_translator</code>. In many heavily loaded server-side cases, it really saved me from becoming a rabbit stew. The idea behind <code>_set_se_translator</code> is to convert SEH exceptions (like access violations, divisions by zero, etc.) into C++ exceptions, which then are handled in the usual C++ way (with destructors called etc.); details can be found on the MSDN page on <code>_set_se_translator </code>[<a href="#[MSDN]">MSDN</a>].</p>

<p>In particular, such a thing is extremely useful if you have a state-machine-based server processing incoming messages. If an access violation (or division by zero) happens during the processing of one message, and it doesnâ€™t cause any memory damage (which is very common with access violations and always happens with division by zero), it is usually perfectly ok to ignore such a message and continue to serve the others without crashing.</p>

<p>One should note that using <code>_set_set_translator</code> and catching resulting C++ exceptions is very different from trying to catch SEH exceptions with <code>catch( ... )</code>. When trying to catch SEH with <code>catch( ... )</code>, no C++ destructors are called between the point where SEH is raised and where it is caught; this can cause all kinds of weird effects (and if youâ€™re using destructors to remove mutex locks, forget catching SEHs with <code>catch( ... )</code>). On the contrary, when using <code>_set_se_translator</code>, SEH is converted into a C++ exception right where SEH occurs, so it is a C++ exception which is thrown. All destructors from the point where SEH was raised, to the point where the C++ exception is caught, are properly called, with much better results (unless memory has already been corrupted by the point where SEH has occurred).</p>
<p>Unfortunately, the last time I checked (which was admittedly a few years ago) similar functionality was not available for *nix C++ compilers, including GCC. Theoretically, it might be possible to throw a C++ exception from the signal handler, but this functionality is platform-dependent and in practice, I wasnâ€™t able to find a platform where it works :-(.</p>

<h2>Recipe #2 â€“ Containers with â€˜moveâ€™ semantics</h2>

<p>Recipe #2 is admittedly a rather weird one, but every good cookbook should contain at least one weird recipe, so here goes. In high-performance code, there are scenarios, where you need to have a container which stores complex objects (such objects including allocated storage etc.), but those objects are only moved around and are never copied. Providing a copy constructor for such objects can be either difficult (for example, if such an object includes a file handle) or undesirable for performance reasons (if such an object contains allocated memory, copying which would be expensive). One common way to deal with this is to use some kind of reference-counted pointer (or something similar to <code>auto_ptr&lt;&gt;</code>); this is a viable option, but it has the associated cost of extra allocation/deallocation, and in really high-performance code, this might be an issue. In such cases, an approach similar to the following could help (rephrasing a proverb, you could say that weird times require weird measures) â€“ see Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
//class X is our complicated class

class StackOfX {
  // stack is just one example; any other type of
  // container (including maps, sets, lists, etc.)
  // can be written in a similar manner
  struct ShadowX { char data[ sizeof(X) ]; };
  typedef vector&lt; ShadowX &gt; ShadowV;
  ShadowV v;

  void push( /* move-in */ X&amp; x ) {
    ShadowX&amp; sx = (ShadowX&amp;)x;
    v.insert( v.end(), sx );
  }
  const X&amp; operator[]( int i ) const {
    return (const X&amp;)v[ i ];
  }

  void pop( /* move-out */ X&amp; x ) {
    ShadowV::iterator it = v.end() - 1;
    ShadowX&amp; sx = (ShadowX&amp;)x;
    sx = *it;
    v.erase( it );
  }

  ~StackOfX() {
    for( ShadowV::iterator it = v.begin();
         it != v.end(); ++it ) {
      X&amp; x = (X&amp;)(*it);
      x.X::~X();
    }
  }
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>While other operations on such a container may be added in a similar way, it is extremely important to keep all such operations within this class, and not to expose any operations of an underlying â€˜shadowâ€™ container to outside world without ensuring the integrity of our <code>StackOfX</code> container.</p>

<h2>Recipe #1 â€“ asserts</h2>

<p>And my top place goes to a very simple, but extremely useful, recipe, related to <code>assert</code>s. In the C/C++ world, everybody knows about <code>assert</code>s; the problem with a standard <code>assert()</code> is that it calls <code>abort()</code> if assertion fails, which is often a bit too much.</p>

<p>The idea of this recipe is very simple â€“ to create a <code>MYASSERT</code> macro which, if violated, throws an exception.</p>

<pre class="programlisting">
  #define MYASSERT( cond ) \ 
    (void)( ( cond ) || ( throw MyAssertException \
    (   #cond, __FILE__, __LINE__ ), 0 ) )</pre>

<p>What exactly your <code>MyAssertException</code> class should be, where to place it in the exception hierarchy, and how to use file name, line number, and the assertion failure is up to you. For example, if youâ€™re concerned about revealing information about your code to the customer, you can easily omit <code>#cond</code> in the production compile, and track what has happened in production based only on file/line. (You do have tags in your source control for all the versions released to production, donâ€™t you?)</p>

<p>Often, several such <code>MYASSERT</code>s are introduced (<code>MYASSERT</code>, <code>MYASSERT2</code>, <code>MYASSERT3</code>, <code>MYASSERT4</code>, etc.) to indicate the level at which the check is performed. For example, you can easily create a header which would behave as follows: if you define <code>MYASSERTLEVEL=2</code>, then all <code>MYASSERT</code>s with <code>level &lt;= 2</code> are checked, and all the others are ignored:</p>

<pre class="programlisting">
  #if MYASSERTLEVEL &gt;= 2
    #define MYASSERT2( cond )  \
    (void)( ( cond ) || ( throw MyAssertException \
    ( #cond, __FILE__, __LINE__ ), 0 ) )
  #else
   #define MYASSERT2() ((void) 0)
  #endif</pre>

<p>Apparently, it is often a good idea to leave at least some of the <code>MYASSERT</code>s in the production code (especially if you run it on your own server or have a mechanism to send logs back to you). If you find that occasionally certain <code>MYASSERT</code>s in production mode fail, this clearly warrants an investigation.</p>

<p>In addition, if youâ€™re using 3rd-party libraries which use the standard <code>assert()</code> internally, it is often a good idea to replace the standard <code>assert() </code>with <code>MYASSERT()</code> to avoid situations when the whole server calls <code>abort()</code> because some assertion within a 3rd-party library has failed (while recovery was still perfectly possible). How you do it depends on the specifics of your project, but it usually can be done either via redefining standard <code>assert()</code> and recompiling the 3rd-party library, or if  <code>assert()</code> calls some helper function on your platform, this helper function can often be replaced to achieve the desired effect.</p>

<img src="http://accu.org/content/images/journals/ol113/Ignatchenko/Ignatchenko-1.png"/>

<h2>References</h2>

<p class="bibliomixed"><a id="[Loganberry04]"></a>[Loganberry04] David â€˜Loganberryâ€™, Frithaes! â€“ an Introduction to Colloquial Lapine!, <a href="http://bitsnbobstones.watershipdown.org/lapine/overview.html">http://bitsnbobstones.watershipdown.org/lapine/overview.html</a></p>

<p class="bibliomixed"><a id="[MSDN]"></a>[MSDN] â€˜_set_se_translatorâ€™ <a href="http://msdn.microsoft.com/en-us/library/5z4bw5h5%28v=vs.110%29.aspx">http://msdn.microsoft.com/en-us/library/5z4bw5h5%28v=vs.110%29.aspx</a></p>


<h2>Acknowledgement</h2>

<p>Cartoon by Sergey Gordeev from Gordeev Animation Graphics, Prague.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
