    <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  :: Code Critique Competition 112</title>
        <link>https://members.accu.org/index.php/articles/2519</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 + Student Code Critiques from CVu journal. + CVu Journal Vol 30, #3 - July 2018</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/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</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/c77/">CVu</a>

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+183+387/">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;Code Critique Competition 112</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 03 July 2018 16:27:33 +01:00 or Tue, 03 July 2018 16:27:33 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Set and collated by Roger Orr. A book prize is awarded for the best entry.</p>
<p><strong>Body:</strong>&nbsp;<p class="EditorIntro">Please note that participation in this competition is open to all members, whether novice or expert. Readers are also encouraged to comment on published entries, and to supply their own possible code samples for the competition (in any common programming language) to scc@accu.org.</p>

<p class="EditorIntro">Note: If you would rather not have your critique visible online, please inform me. (Email addresses are not publicly visible.)</p>

<h2>Last issueâ€™s code</h2>

<p class="blockquote">Iâ€™m playing around with simple increasing sequences of small numbers and seeing what various different generators produce. I had problems that sometimes the result was wrong â€“ for example if I produce a number that overflows the integer size Iâ€™m using â€“ and so I added a postcondition check that the output sequence is increasing. However, Iâ€™ve found the check doesnâ€™t always â€˜fireâ€™ â€“ it works with gcc with or without optimisation but fails with MSVC <em>unless</em> I turn on optimisation. Iâ€™ve produced a really simple example that still shows the same problem, can you help me see whatâ€™s wrong?</p>

<p class="blockquote"><em>Expected</em> output, showing the postcondition firing:</p>

<pre class="programlisting">
    1,2,3,4,5,6,7,8,9,10,
    1,3,6,10,15,21,28,36,45,55,
    1,1,2,3,5,8,13,21,34,55,
    1,5,14,30,55,91,140,204,285,385,
    Postcondition failed!
    1,5,14,30,55,91,-116,-52,29,-127,</pre>
	
<p>Can you help (and perhaps identify one or two other issues en route)? The code is in Listing 1. (Unfortunately, the first few lines from <code>fibonacci()</code> didnâ€™t appear in the printed copy of <em>CVu</em>. We apologise for the confusion this caused.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;iostream&gt;
#include &lt;iterator&gt;
#include &lt;vector&gt;
class postcondition
{
public:
  postcondition(std::function&lt;bool()&gt; check)
  : check_(check) {}
  ~postcondition()
  {
    if (!check_())
      std::cerr &lt;&lt; &quot;Postcondition failed!\n&quot;;
  }
private:
  std::function&lt;bool()&gt; check_;
};
template&lt;typename T&gt;
std::vector&lt;T&gt; get_values(int n,
  std::function&lt;T(T)&gt; generator)
{
  std::vector&lt;T&gt; v;
  auto is_increasing = [&amp;v]() {
    return is_sorted(v.begin(), v.end()); };
  postcondition _(is_increasing);
  T j = 0;
  for (int i = 0; i != n; ++i)
  {
    j = generator(j);
    v.push_back(j);
  }
  return v;
}

using out = std::ostream_iterator&lt;int&gt;;
template &lt;typename T&gt;
void sequence()
{
  auto const &amp; result = get_values&lt;T&gt;(10,
    [](T i) { return i + 1; });
  std::copy(result.begin(), result.end(),
    out(std::cout, &quot;,&quot;));
  std::cout &lt;&lt; std::endl;
}
template &lt;typename T&gt;
void triangular()
{
  T i{};
  auto const &amp; result = get_values&lt;T&gt;(10,
    [&amp;i](T j) { return j + ++i; });
  std::copy(result.begin(), result.end(),
    out (std::cout, &quot;,&quot;));
  std::cout &lt;&lt; std::endl;
}
template &lt;typename T&gt;
void fibonacci()
{
  T i{1};
  auto const &amp; result = get_values&lt;T&gt;(10,
    [&amp;i](T k) { std::swap(i, k); return i + k; });
  std::copy(result.begin(), result.end(),
    out (std::cout, &quot;,&quot;));
  std::cout &lt;&lt; std::endl;
}
template &lt;typename T&gt;
void sum_squares()
{
  T i{1};
  auto const &amp; result = get_values&lt;T&gt;(10,
    [&amp;i](T j) { return j + i * i++; });
  std::copy(result.begin(), result.end(),
    out (std::cout, &quot;,&quot;));
  std::cout &lt;&lt; std::endl;
}
int main()
{
  sequence&lt;int&gt;();
  triangular&lt;int&gt;();
  fibonacci&lt;int&gt;();
  sum_squares&lt;int&gt;();
  sum_squares&lt;char&gt;(); // overflow expected
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<h2>Critiques</h2>

<h3>Balog Pal</h3>

<p><p class="blockquote">â€œI produce a number that overflows the integer size Iâ€™m using â€“ and so I added a postcondition check that the output sequence is increasing.â€œ</p>

<p>Hmm. Signed integer overflow is undefined behavior. If we have that in the program, postcondition checks will not help â€“ or reliably detect problems. Letâ€™s see the code if it is indeed the source of the problems.</p>

<p>First, just a fast read from the top making notes of other problems.</p>

<p>The postcondition class has a converting ctor, we probably want an <code>explicit</code> here. It takes function by value, probably following some outdated wisdom on passing predicates by value. I learned the hard way that <code>std::function</code> is a fat beast and pass it around as const ref. Though for this case we make a copy of what is passed, so the preferred way is probably indeed taking it by value, but then move in instead of creating yet another copy.</p>

<p>Formally weâ€™re violating the rule of 3, but the intended use form will not lead to problems. The industrial version would probably inherit from <code>nocopy</code> and possibly require <code>noexcept</code> for the check function too. I guess the idea about using the check in dtor is to cover all exit paths automatically instead of explicit points. Thatâ€™s fine, but we need to be extra careful about object dependencies, avoid accessing objects in the check function that were already destructed.</p>

<p><code>check_(check)</code> is a form I avoid and use the same name for member variable and parameter, experience shows that this is less error prone in general, unless the compiler has reliable warning on mistakes made when writing <code>check_(check_)</code>.</p>

<p><code>get_values</code> again takes function by value. Whatâ€™s worse, it takes function for no good reason I can imagine. Itâ€™s a template, should just have another parameter for type of passed generator and take the source without repackaging it. It uses the postcondition with a lambda, the dependency chain looks fine at glance. Weâ€™re calling the generator with the previous aggregate and just storing it in a vector. The check also looks okay, with all the <code>std::</code> noise around (what I would not have in my code) it is odd to see the naked <code>is_sorted</code>, but it should work via ADL.</p>

<p>Then we have the sample sequence functions. With obvious blatant copy-paste for the printout part. That at least should be extracted into a function, but my preferred way would separate responsibilities and just return the vector with the sequence and have an outer framework that used these and arrange the printing or whatever other work.</p>

<p>In the implementation I prefer the initial value look <code>i = 0;</code> and <code>i = 1;</code> instead of the <code>{1}</code> and especially the <code>{}</code> form. I also note that naming of the local and lambda param would fare well in IOCCC, so weâ€™ll look ahead to deciphering what is really going on. It also shows that the interface is weak on design: it would be so much easier if we got both the sequence number and the aggregate as argument.</p>

<p><code>auto const &amp; result = get_values</code> is okay, we get life-extension on the result coming from the function. But these days I prefer just <code>auto const</code> as copy-elision is reliable for construction, and for the <code>&amp;</code> case, the compiler is actually allowed to make a copy if it feels like it. Making the difference moot.</p>

<p>Letâ€™s check the generator lambdas. For sequences, thereâ€™s little chance of getting it wrong. In <code>triangular</code> we increment <code>i</code>, that is correctly captured by ref (and explicitly too).</p>

<p><code>fibonacci</code> deviates from all traditions that would use 2 values and roll them. Instead it struggles with just one. It looks to work through evil trickery, at least for types covered by <code>std::swap</code>. Which should be switched to the <code>using std::swap;</code> followed by unqualified call to pick up possible user-defined overloads, not just specialisations.</p>

<p><code>sum_squares</code> has <code>i * i++</code>. Wow. We were looking for UB, but not this one. :) Iâ€™m skipping this discussion; if anyone is interested, please read the gigabytes we typed over the last 30 years about <code>i + i++</code> and similar expressions. This one is not covered even by the recent refining of the order of evaluation for C++17 (P0145R3) and we have an explicit example in the execution section. But even if <code>++</code> was reliably sequenced at <code>i++</code>, the outcome would still be unspecified and we may generate the wrong number depending on whether the increment happens before or after reading the first <code>i</code>. The fixed form should create the value first and do the increment afterward.</p>

<p>Finally, <code>main</code> leaves nothing to note. After we have fixed the previous problems, the <code>int</code> versions should work fine. The <code>char</code> version is indeed bound to overflow, letâ€™s look where. The lambda in <code>sum_squares</code> would be the obvious candidate, but it is actually okay: the expression has <code>char</code> type inside that gets promoted to <code>int</code>, the <code>+</code> and <code>*</code> are calculated on <code>int</code> without overflow and the return type, as we didnâ€™t say otherwise is <code>int</code> too.</p>

<p>So, UB dodged here; <code>j = generator(j);</code> must be the place where we narrow the <code>int</code> down to <code>char</code>. The MSVC compiler actually flags it for us, but not at that place: it is lost in the preceding lines of code. And this line is not picked anywhere. Ah, and it is right too: at that spot we call <code>generator()</code> that is a <code>T(T)</code> function and we store <code>char</code> as <code>char</code>. The narrowing magic is done inside the dark corners of <code>std::function</code> where it adapts our <code>int(char)</code> lambda. And with all the type-punning around even the compiler canâ€™t tell us the point.</p>

<p>Anyway, what we have is not an overflow in an expression but a narrowing conversion. Which is not UB, â€˜justâ€™ providing an implementation-defined value for the out-of-range case. And the values we saw in the vector suggest we got negative values and CAN expect the postcondition check to fire. I definitely missed something during the code reading.</p>

<p>In MSVC, I can usually debug inside lambdas and other odd locations, but no luck in this case. The breakpoint on the postcondition check just never triggers, despite it being called. So I wrote some dump code inside <code>check</code>. And found that in debug mode the vector <code>v</code> is empty. Thus passing the sorted check with flying colors....</p>

<p>DOH. My working theory is that we are hit by NRVO/move semantics. In <code>get_values</code>, we return a vector by value, and do that from a local variable named <code>v</code>. At return point <code>v</code> is considered xvalue so returning it via <code>move</code> is fair game. And in that case the content is moved out from <code>v</code> to the temporary that gets actually returned. Then the destructors are called and the check is executed on the â€˜unspecified-though-validâ€™ state of the eviscerated <code>v</code>. That happens to look empty, but could be anything really. While in release build, the compiler probably uses NRVO, avoiding the copy/move completely. <code>v</code> never exists as a local variable but gets constructed at the callerâ€™s location, so the check function sees its content.</p>

<p>As experiment, I tried <code>return std::move(v);</code> in <code>get_values</code>, that kills NRVO and with that MSVC release mode became consistent with debug, and <code>check</code> was looking at empty vector in both.</p>

<p>Though it makes sense the way we saw, I made an extra check in the standard. And indeed, 9.6.3p3 clearly states:</p>

<p class="blockquote">The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables (9.6) of the block enclosing the return statement.</p>

<p>So we better commit an extra bullet to the check list on destructor-dependencies with the case of move-from-return beyond the early destruction cases.</p>

<h3>James Holland</h3>

<p>The problem with the studentâ€™s code is associated with the return statement of <code>get_values()</code>. It seems to me that in debug mode, the vector <code>v</code> is being affected in some way before the destructor of <code>postcondition</code> is called. It is probable that Named Return Value Optimisation (NRVO) is employed resulting in the contents of <code>v</code> being moved to the calling function. This would leave <code>v</code> in a valid but unknown state. I suspect, in this case, <code>v</code> has been left with zero length. Furthermore, I suspect that the destructor of <code>postcondition</code> reads the modified value of <code>v</code> and finds it empty. If this is the case, postcondition will conclude that <code>v</code> is sorted and not produce a warning message. (An empty string is considered sorted.)</p>

<p>To my mind, this is incorrect behaviour. If NRVO takes place by means of moving (as opposed to copying) the contents of <code>v</code>, then the destructor should inspect the location to where the contents of <code>v</code> has been moved. The destructor will then conclude that the string is not sorted, as expected. Alternatively, moving the contents of <code>v</code> should be prohibited if a reference to it is made by a destructor.</p>

<p>When the optimiser is enabled, I assume different code is generated that either calls the destructor of <code>postcondition</code> before any manipulation of <code>v</code> or does not move <code>v</code>. Either way, this would result in the destructor of <code>postcondition</code> seeing <code>v</code> with its original contents and conclude that the vector is not ordered and produce a warning message.</p>

<p>It is strange (and somewhat worrying) that the program behaviour is dependent on whether the optimiser is enabled. The conclusion is that Visual Studio is producing incorrect code when the optimiser is disabled, i.e. in debug mode.</p>

<p>Probably the simplest way to ensure that the destructor of postcondition is invoked before the value of <code>v</code> is returned from <code>get_values()</code> is to add a pair of braces as shown below.</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  std::vector&lt;T&gt; get_values(int n,
    std::function&lt;T(T)&gt; generator)
  {
    std::vector&lt;T&gt; v;
    auto is_increasing = [&amp;v]()
      {return is_sorted(v.begin(), v.end());};
    { // Enclose postcondition in a new scope.

      postcondition _(is_increasing);
      T j = 0;
      for (int i = 0; i != n; ++i)
      {
        j = generator(j);
        v.push_back(j);
      }
    } // Enclose postcondition in a new scope.

    return v;
  }</pre>
  
<p>The destructor of <code>postcondition</code> will be called when the newly added closing brace is encountered. This is just before the <code>return</code> statement as required. The amendment produces expected results both in debug mode and release mode.</p>

<p>There is one other important matter to consider, that of undefined behaviour. The function <code>sum_squares()</code> contains a lambda with the code return <code>j + i * i++;</code>. This is problematic because it is not known when, during the evaluation of the expression, the variable <code>i</code> will be incremented. The result of the expression depends on when <code>i</code> is incremented. To produce a defined result, the <code>return</code> statement should be split into three separate statements as shown below.</p>

<pre class="programlisting">
  const auto k = i;
  ++i;
  return j + k * k;</pre>
  
<p>Finally, within the templated functions that generate the sequences, the student has defined the variable result as <code>auto const &amp;</code>. This is perfectly valid syntax but it does give the impression that result is a reference to another variable that has been declared in the source code. This is not the case. What the compiler does, in effect, is to create a temporary variable and initialises it with the value returned from <code>get_values()</code>. The compiler then uses the value of the temporary variable to initialise the reference variable result. This is permitted because result is <code>const</code>. Had result been defined as non-<code>const</code>, the compiler would have issued an error message because changing the value of result (that refers to a temporary) does not make any sense as the temporary variable will soon disappear. The outcome of this is that initialising a <code>const &amp;</code> variable has the same effect as initialising a <code>const</code> variable. Given this, I suggest removing the <code>&amp;</code> from the definitions.</p>

<h3>Jason Spencer</h3>

<p>The headline bug here is caused by a possible optimisation that the compiler might perform and it may remove the values from <code>v</code> in <code>get_values</code> before they are checked.</p>

<p>Note that there is actually a typo in the print and PDF versions of this Critique â€“ the <code>fibonacci()</code> function is missing the first three lines of the function. It was correct in the mailing-list announcement, on which this response is based.</p>

<p>To understand what is happening in <code>get_values</code>, we need to understand how the compiler generates code to manipulate the stack when a function is called. Typically space is reserved on the stack for the return value â€“ since weâ€™re returning a vector letâ€™s call the object in this space <code>vret</code>. Space for the variables local to the function (including <code>v</code>) is then reserved on the stack. The variables are located in this space in the order in which they are declared within the function, and theyâ€™re constructed in this order too. They are destructed in the opposite order to their construction.</p>

<p>When the return statement is executed, <code>v</code> is either copied (by copy constructor), or (since C++11) moved into <code>vret</code>. It is also possible for the copy/move to be elided, and for <code>v</code> to actually be in the space assigned for <code>vret</code> â€“ this is called Return Value Optimisation (RVO) â€“ specifically Named RVO (NRVO) because weâ€™re not constructing the return value in the return statement, weâ€™re returning a variable. This copy elision can occur whether there are side-effects of copying/moving or not.</p>

<p>Whether return by copy construction, move construction, or copy elision occurs depends a lot on the compiler, the compiler version, the flags used and the optimisation level, hence the complicated nature of the behaviour the student found.</p>

<p>The student was expecting <code>_</code> to be destroyed before <code>v</code>, and it will be. But we now face three possible scenarios at the destruction of <code>_</code>:</p>

<ul>
	<li><code>v</code> was <em>copied</em> to <code>vret</code> at the <code>return</code> statement â€“ in which case, <code>v</code> is still valid and the test behaves as expected.</li>
	
	<li><code>v</code> was <em>moved</em> to <code>vret</code> at the <code>return</code> statement â€“ in which case, <code>v</code> is now empty and the test <em>always</em> passes because a vector with less than two values still causes <code>is_increasing</code> to return true.</li>
	
	<li><code>v</code> <em>is</em> <code>vret</code> due to NRVO â€“ in which case, the test behaves as expected.</li>
</ul>

<p>It is the second scenario that prevents the error from appearing when it is expected.</p>

<p>The details of copy/move/RVO optimisations can be found at <a href="#[1]">[1]</a> and <a href="#[2]">[2]</a>.</p>

<p>The other issues Iâ€™d comment on are:</p>

<ul>
	<li>Iâ€™m not sure using <code>postcondition</code> to test is a good idea. The destructor, and therefore the test, will also be executed if an exception is thrown and not caught in <code>get_values</code> (thrown by a generator perhaps). The student may want to test <code>std::current_exception</code> in <code>~postcondition</code> before calling the test. And of course the test canâ€™t throw anything, so should probably be <code>noexcept</code>. Consider a templated function as a test that doesnâ€™t rely on RAII.</li>
	
	<li>Implicit casting of output to <code>int</code>:
		<p>Since <code>out</code> is an alias for <code>std::ostream_iterator&lt;int&gt;</code> and it is used in the <code>sequence&lt;T&gt;</code>, <code>triangular&lt;T&gt;</code>, <code>fibonacci&lt;T&gt;</code> and <code>sum_square&lt;T&gt;</code> templates, the output sequence values, which should contain values of type <code>T</code>, are cast to <code>int</code> before being output. So if <code>sum_squares&lt;float&gt;;</code> is included in <code>main()</code> the values are truncated and printed as <code>int</code>s.</p></li>
		
	<li>The generator functions should do type checking on <code>T</code>, and potentially disable themselves for types that donâ€™t support the operators used, or for types that would produce nonsensical results.
		<p>For example, <code>fibonacci&lt;std::string&gt;()</code> will work, but <code>fibonacci&lt;std::complex&lt;float&gt;&gt;()</code> wonâ€™t. <code>T</code> has to support one or more of: <code>operator++</code>, <code>operator+</code> and must have a <code>std::swap</code> overload depending on the generator. <code>T::operator&lt;</code> is also required for the <code>is_increasing</code> test. Consider an <code>enable_if</code> <a href="#[3]">[3]</a> with <code>std::is_arithmetic</code> <a href="#[4]">[4]</a> and <code>std::is_swappable</code> <a href="#[5]">[5]</a> in the simplest case.</p></li>
</ul>
		
<p>In terms of design Iâ€™d look more into the overflow checking and the generators.</p>

<p>The issue of robustly checking overflow is a complicated one and often involves tests alongside the operations, rather than testing the result, as was the case here. Overflow detection isnâ€™t that difficult to do in theory â€“ most CPUs have an overflow flag (OF) which is set when the last ALU operation resulted in a value that overflowed the output register. You might also want to check the carry flag (CF) <a href="#[6]">[6]</a>. The problem is that thereâ€™s no straightforward way of detecting this in C++. We could write inline assembler functions that perform the arithmetic operation and copy the OF flag to a local variable and act based on the state of that, but this would be architecture specific. It also limits optimisation â€“ for example a typical compiler would swap a multiplication by a constant 8 into a left shift by 3, but this code wouldnâ€™t.</p>

<p>Another approach <a href="#[7]">[7]</a> is to, for each operation type, check that the output variable has enough capacity â€“ this typically involves finding the position of the most significant set bit. An unsigned integer multiplication of variables A and B will never use more than MSB_A+MSB_B bits in the output, where MSB_A is the position of the MSB in A. The unsigned integer addition of A and B will never use more bits than MAX(MSB_A,MSB_B)+1. And so on.</p>

<p>Most compilers also have options to trap on overflow for arithmetic, but it can be complicated to handle this at runtime, and is compiler specific.</p>

<p>There are some mathematical functions in C++ that do support overflow detection in a portable and robust way. For example <code>std::math_errhandling</code> <a href="#[8]">[8]</a> can be used to detect some overflow and other conditions for floating point types.</p>

<p><code>std::overflow_error</code>, while sounding interesting is only thrown by <code>std::bitset</code> conversion functions, and not general purpose arithmetic, but thereâ€™s no reason not to use it in bespoke overflow testing code.</p>

<p>Another approach is to create a special type that wraps the arithmetic type, overloads the arithmetic operators, and checks for overflow after every operation. For example <a href="#[9]">[9]</a>.</p>

<p>Yet another approach is to perform the operation on a larger (similarly signed) data type and cast to the requested type at the end, checking for truncation after the cast. This might not however catch all cases of overflow at every intermediary operation (or in fact the overflow may be required behaviour â€“ an implicit modulo).</p>

<p>Iâ€™m not a fan of using <code>is_increasing</code> because although the program spec says the sequences are increasing, it is possible for aliasing to occur â€“ for example, in a <code>sum_squares&lt;uint8_t&gt;</code> sequence, at the sixteenth term 256 is added to the running total â€“ this overflows, but the total remains the same, and that term at least would pass the test (although earlier terms might not). Iâ€™m sure there are many other such examples.</p>

<p>Regarding the generators â€“ theyâ€™re not very versatile the way they are written here. Iâ€™d consider implementing them either as iterators, or as generator functors. In the current design the state of the sequence is store in variable <code>i</code>, which is a nice design, but if it were stored in an object then the object can be copied, reset, etc.. something like this:</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  class arithmetic_progression_ {
    T n;
    T step;
  public:
    typedef T result_type;
    arithmetic_progression_ (const T n = 0,
      const T step = 1) : n(n), step(step) {}
    T operator()() {
      n += step;
      return n;
    }
    T get_last() { return n; }
  };
  template &lt;typename T&gt; class triangular_ {
    T n;
    T level;
  public:
    typedef T result_type;
    triangular_ (const T n = 0,
      const T level = 1) : n(n), level(level) {}
    T operator()() {
      n += level++;
      return n;
    }
    T get_last() { return n; }
  };
  template &lt;typename T&gt; class sum_squares_ {
    T n;
    T level;
  public:
    typedef T result_type;
    sum_squares_ (const T n = 0,
      const T level = 1) : n(n), level(level) {}
    T operator()() {
      n += level * level++;
      return n;
    }
    T get_last() { return n; }
  };</pre>
  
<p>This is much more versatile because you can now generate as many values as you like (<code>25</code> in the example below):</p>

<pre class="programlisting">
  std::vector&lt;int&gt; v;
  std::generate_n ( std::back_inserter(v), 25,
    triangular_&lt;int&gt;() );
  std::copy ( std::begin(v), std::end(v),
    std::ostream_iterator&lt;int&gt;(std::cout, &quot;,&quot;) );
  std::cout &lt;&lt; '\n';</pre>
  
<p>Or you can use an iterator wrapper (such as the Boost Generator Iterator Adaptor <a href="#[10]">[10]</a>) to print the sequence directly to any output stream:</p>

<pre class="programlisting">
  arithmetic_progression_&lt;int&gt; a_p;
  std::copy_n (
    boost::make_generator_iterator( a_p ), 15,
    std::ostream_iterator
      &lt;decltype(a_p)::result_type&gt;
      (std::cout, &quot;,&quot;) );
  std::cout &lt;&lt; '\n';</pre>
  
<p>Something to also consider is whether it wouldnâ€™t be beneficial to generate sequences at compile time. In the past this meant using templates <a href="#[11]">[11]</a>, but there are now more options with <code>constexpr</code> <a href="#[12]">[12]</a>:</p>

<pre class="programlisting">
  constexpr int factorial(int n)
  {
    return n &lt;= 1 ? 1 : (n * factorial(n - 1));
  }</pre>
  
<p>When it comes to generators inspiration can be taken from C# and Python. Paolo Severini <a href="#[13]">[13]</a> has an extensive write-up comparing C# and C++ generators and their implementation. He also looks at co-routine approaches.</p>

<h4>References</h4>

<p class="bibliomixed"><a href="https://en.cppreference.com/w/cpp/language/copy_elision">[1]https://en.cppreference.com/w/cpp/language/copy_elision</a><a id="[1]"></a></p>

<p class="bibliomixed"><a href="https://shaharmike.com/cpp/rvo/">[2]	https://shaharmike.com/cpp/rvo/</a><a id="[2]"></a></p>

<p class="bibliomixed"><a href="https://eli.thegreenplace.net/2014/sfinae-and-enable_if/">[3]	https://eli.thegreenplace.net/2014/sfinae-and-enable_if/</a><a id="[3]"></a></p>

<p class="bibliomixed"><a href="http://en.cppreference.com/w/cpp/types/is_arithmetic">[4]	http://en.cppreference.com/w/cpp/types/is_arithmetic</a><a id="[4]"></a></p>

<p class="bibliomixed"><a href="http://en.cppreference.com/w/cpp/types/is_swappable">[5]	http://en.cppreference.com/w/cpp/types/is_swappable</a><a id="[5]"></a></p>

<p class="bibliomixed"><a href="http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt">[6]	http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt</a><a id="[6]"></a></p>

<p class="bibliomixed"><a href="https://stackoverflow.com/questions/199333/how-to-detect-integer-overflow">[7]	https://stackoverflow.com/questions/199333/how-to-detect-integer-overflow</a><a id="[7]"></a></p>

<p class="bibliomixed"><a href="http://en.cppreference.com/w/cpp/numeric/math/math_errhandling">[8]	http://en.cppreference.com/w/cpp/numeric/math/math_errhandling</a><a id="[8]"></a></p>

<p class="bibliomixed"><a href="https://accu.org/index.php/journals/324">[9]	https://accu.org/index.php/journals/324</a><a id="[9]"></a></p>

<p class="bibliomixed"><a href="https://www.boost.org/doc/libs/1_62_0/libs/utility/generator_iterator.htm">[10]	https://www.boost.org/doc/libs/1_62_0/libs/utility/generator_iterator.htm</a><a id="[10]"></a></p>

<p class="bibliomixed"><a href="https://www.jasonspencer.org/articles/series/">[11]	https://www.jasonspencer.org/articles/series/</a><a id="[11]"></a></p>

<p class="bibliomixed"><a href="https://en.cppreference.com/w/cpp/language/constexpr">[12]	https://en.cppreference.com/w/cpp/language/constexpr</a><a id="[12]"></a></p>

<p class="bibliomixed"><a href="https://paoloseverini.wordpress.com/2014/06/09/generator-functions-in-c/">[13]	https://paoloseverini.wordpress.com/2014/06/09/generator-functions-in-c/</a><a id="[13]"></a></p>

<h2>Commentary</h2>

<p>As all three entries explain, the cause of the differences in behaviour is an interaction between destructors and generating the return value. The â€˜featureâ€™ was added to C++11 when move semantics were added to the language and returning from a named local variable was allowed to <em>move</em> the value. I do not know at what point in the process anyone realised that this change could cause the difficulties that this critique demonstrates.</p>

<p>I think the critiques between them covered most of the points in the critique.</p>

<h2>The winner of CC 111</h2>

<p>The critiques all detected the problem with the unpredictable behaviour, but James additionally provided a solution to the troublesome behaviour â€“ using an extra scope to ensure the destruction occurs before the return.</p>

<p>As Pal stated, the problem with signed overflow is that this produces undefined behaviour and attempting to detect this can be troublesome. This is an active area of discussion on the C++ committee...</p>

<p>Using destruction to verify post-conditions can have problems, as Jason points out, because of the danger of throwing an exception while unwinding from an exception, which will simply terminate the program.</p>

<p>Both Pal and James pointed out the UB in <code>sum_squares</code> in the expression <code>j + i * i++</code> but James additionally provided some code for a correct replacement.</p>

<p>All three critiques gave the code a good look, but on balance I consider Jamesâ€™ critique was the most helpful to the person with the problematic code so I have awarded him the prize for this issue.</p>

<h2>Code Critique 112</h2>

<h3>(Submissions to scc@accu.org by Aug 1st)</h3>

<p class="blockquote">Further to articles introducing D, I am attempting to use the event-driven Vibe.d server library, which I understand to be like a native version of Pythonâ€™s Tornado and potentially a â€˜killer appâ€™ of D as I havenâ€™t seen any other mature event-driven server library in a compiled language.</p>

<p class="blockquote">I would like to build a back-end server that performs some processing on the body of the HTTP request it receives. To begin with, I would like it to simply echo the request body back to the client.</p>

<p class="blockquote">My code works but there are three problems: (1) when I issue a POST request with lynx, 3 spaces are added to the start of the response text, (2) I cannot test with nc because it just says 404 and doesnâ€™t log anything, and (3) Iâ€™m worried that reading and writing just one byte at a time is inefficient, but I canâ€™t see how else to do it: I raised a â€˜more documentation neededâ€™ bug at <a href="https://github.com/vibe-d/vibe.d/issues/2139">https://github.com/vibe-d/vibe.d/issues/2139</a> but at the time of writing nobody has replied (should I have used a different forum?)</p>

<p>The code is in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
import vibe.d;
void main() {
  auto settings = new HTTPServerSettings;
  settings.port = 8080;
  listenHTTP(settings, (req, res) {
    ubyte[1] s;
    while(!req.bodyReader.empty()) {
      req.bodyReader.read(s);
      res.bodyWriter.write(s);
    }
  });
  runApplication();
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>You can also get the current problem from the accu-general mail list (next entry is posted around the last issueâ€™s deadline) or from the ACCU website (<a href="http://accu.org/index.php/journal">http://accu.org/index.php/journal</a>). This particularly helps overseas members who typically get the magazine much later than members in the UK and Europe.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
