    <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 106</title>
        <link>https://members.accu.org/index.php/articles/2393</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 + CVu Journal Vol 29, #3 - July 2017</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/c77/">CVu</a>

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+375/">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 106</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 02 July 2017 17:41:54 +01:00 or Sun, 02 July 2017 17:41:54 +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 was writing a simple program to analyse the programming languages known by our team. In code review I was instructed to change <code>languages()</code> method in the programmer class to return a <code>const</code> reference for performance. However, when I tried this the code broke. Iâ€™ve simplified the code as much as I can: can you help me understand whatâ€™s wrong? It compiles without warnings with both MSVC 2015 and gcc 6. I am expecting the same output from both â€˜Original wayâ€™ and â€˜New wayâ€™ but I get nothing printed when using the new way.</p>

<p>The listings are as follows:</p>

<ul>
	<li>Listing 1 is <span class="filename">programmer.h</span></li>
	<li>Listing 2 is <span class="filename">team.h</span></li>
	<li>Listing 3 is <span class="filename">team_test.cpp</span></li>
</ul>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#pragma once
class programmer
{
public:
  // Add a language
  void add_language(std::string s)
  { languages_.push_back(s); }
  // the programmer's languages - original
  std::vector&lt;std::string&gt;
  original() const
  {
    return {languages_.begin(),
            languages_.end()};
  }
  // new - avoid copying for performance
  std::list&lt;std::string&gt; const &amp;
  languages() const
  { return languages_; }
  programmer() = default;
  programmer(programmer const&amp; rhs)
  : languages_(rhs.languages_) {}
  programmer(programmer &amp;&amp;tmp)
  : languages_(std::move(tmp.languages_)) {}
  ~programmer() { languages_.clear(); }
private:
  std::list&lt;std::string&gt; languages_;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#pragma once
#include &lt;map&gt;
class team
{
public:
  // Add someone to the team
  void add(std::string const &amp;name,
    programmer const &amp; details)
  {
    team_.emplace(
      std::make_pair(name, details));
  }
  // Get a team member's details
  auto get(std::string const &amp;name) const
  {
    auto it = team_.find(name);
    if (it == team_.end())
      throw std::runtime_error(&quot;not found&quot;);
    return it-&gt;second;
  }
private:
  std::map&lt;std::string, programmer&gt; team_;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;list&gt;
#include &lt;map&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &quot;programmer.h&quot;
#include &quot;team.h&quot;

int main()
{
  team t;
  programmer p;
  p.add_language(&quot;C++&quot;);
  p.add_language(&quot;Java&quot;);
  p.add_language(&quot;C#&quot;);
  p.add_language(&quot;Cobol&quot;);
  t.add(&quot;Roger&quot;, std::move(p));

  p.add_language(&quot;javascript&quot;);
  t.add(&quot;John&quot;, std::move(p));

  std::cout &lt;&lt; &quot;Original way:\n&quot;;
  for (auto lang : t.get(&quot;Roger&quot;).original())
  {
    std::cout &lt;&lt; lang &lt;&lt; '\n';
  }
  std::cout &lt;&lt; &quot;\nNew way:\n&quot;;
  for (auto lang : t.get(&quot;Roger&quot;).languages())
  {
    std::cout &lt;&lt; lang &lt;&lt; '\n';
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<h2>Critique</h2>

<h3>James Holland</h3>

<p>The problem with the studentâ€™s code lies in the â€˜New wayâ€™ range-based <code>for</code> loop. Calling the <code>get()</code> member function on <code>t</code> results in a temporary object of type <code>programmer</code>. The temporary objectâ€™s <code>languages()</code> function is then called which returns an <code>std::list</code> of <code>std::string</code>s. The range-based <code>for</code> loop then effectively calls <code>begin()</code> on the <code>std::list</code> thus returning an iterator to the list. The iterator will be then compared with the end of the list to determine whether there are any items in the list. Unfortunately, it is around this time (and I must admit I am not exactly sure when) that the temporary <code>programmer</code> object will go out of scope, its destructor called and will no longer be valid. We are now in the realms of undefined behaviour. Anything could happen and we should not be too surprised if nothing is printed.</p>

<p>Obtaining a reference to <code>t</code>â€™s <code>programmer</code> object, instead of making a copy, will result in the range-based <code>for</code> loop referring to a valid list of strings and ultimately in the expected printed output. This can be achieved by amending teamâ€™s <code>get()</code> function to return a reference to a <code>programmer</code> object. As the <code>t</code> object will remain valid while the <code>for</code> loop is executing, there is no need to make a copy.</p>

<p>I think there are other oddities with the studentâ€™s code. The <code>std::move()</code> within the second parameter of the <code>t.add()</code> has no effect as the parameter is being passed by (<code>const</code>) reference. This means object <code>p</code> contains the same programming languages after the call to <code>t.add()</code> as before. This results in John possessing all the programming languages of Roger plus Javascript. This is probably not what was required. If <code>std::move(p)</code> is used, it must be assumed that <code>p</code> is left in a valid but unknown state. It may contain values or it may not. It is best to modify the <code>programmer</code> class to have a public <code>clear()</code> function. This function should then be called before repopulating <code>p</code> with another member of staffâ€™s programming languages.</p>

<h2>Commentary</h2>

<p>The main problem with this critique, as James explained, is holding a reference to a temporary after its destruction. This is, unfortunately, quite easy to do in C++ and the new-style range based <code>for</code> provides a potential site.</p>

<p>In C++ the statement</p>

<pre class="programlisting">
  for (auto lang : t.get(&quot;Roger&quot;).languages()){}</pre>
  
<p>is equivalent to this rewritten block of statements:</p>

<pre class="programlisting">
  {
    auto &amp;&amp;__range = t.get(&quot;Roger&quot;).languages();
    auto __begin = __range.begin();
    auto __end = __range.end();

    for ( ; __begin != __end; ++__begin ) {
      auto lang = *__begin;
      {}
   }
  }</pre>
  
<p>Since <code>languages()</code> returns a <code>const</code> reference to an <code>std::list</code> this means <code>__range</code> in turn is a <code>const</code> reference to an <code>std::list</code> â€“ but the target of the reference is member data of a <em>temporary</em> that is destroyed at the end of the first statement in the re-written code.</p>

<p>Jamesâ€™ solution in this case, of making the <code>get()</code> function return a reference not a copy, solves the problem as <code>__range</code> now refers to an object owned by <code>t</code>, whose lifetime lasts after the end of the <code>for</code> loop, and so there is no longer a â€˜dangling referenceâ€™.</p>

<p>The root cause of the problem is the declaration of the method:</p>

<pre class="programlisting">
  auto get(std::string const &amp;name) const;</pre>
  
<p>Somehow it seems the presence of <code>auto</code> partially disables the programmerâ€™s critical mind. Without <code>auto</code> the programmer, in my experience, is more likely to notice the implied copy in:</p>

<pre class="programlisting">
  programmer get(std::string const &amp;name) const;</pre>
  
<p>and to have written the method to return a reference:</p>

<pre class="programlisting">
  programmer const
    &amp;get(std::string const &amp;name) const;</pre>
	
<p>In other cases, though, this may not be a possible solution (for example, the data returned by <code>get()</code> might be generated during the call). We can make the code safe by binding the temporary to a named variable that outlasts the <code>for</code> loop:</p>

<pre class="programlisting">
  auto temp = t.get(&quot;Roger&quot;);
  for (auto lang : temp.languages()) {}</pre>
  
<p>One drawback with this solution is that the variable introduced remains in scope until the end of the enclosing block; it would be nicer to ensure it gets deleted at the end of the <code>for</code> loop. By a bit of a co-incidence, two proposals published this year would provide alternative ways of making the code safe. (Note that neither proposal has, as yet, been approved by the standards committee.)</p>

<p>Firstly Zhihao Yuanâ€™s proposal P0577R0 (â€˜Keep that temporary!â€™) would allow using the proposed â€˜<code>register</code>â€™ expression to extend the lifetime of the temporary to the end of the loop, using this syntax:</p>

<pre class="programlisting">
  for (auto lang :
    (register t.get(&quot;Roger&quot;)).languages()){}</pre>
	
<p>Secondly Thomas KÃ¶ppeâ€™s proposal P0614R0 (â€˜Range-based <code>for</code> statements with initializerâ€™) would allow using an initializer in a range <code>for</code> loop, using this syntax:</p>

<pre class="programlisting">
  for (auto tmp = t.get(&quot;Roger&quot;);
       auto lang : tmp.languages()){}</pre>
	   
<p>This elegantly ensures the scope of the introduced variable ends at the end of the <code>for</code> loop.</p>

<p>Even if either or both of these proposals are accepted, the underlying problem of <em>indirectly</em> binding a reference to a temporary object remains untouched, and can be hard to diagnose. The problem occurs when chaining method calls where the <em>final</em> call returns a reference but one or more of the intermediate calls return a temporary. This is something a static analysis tool could in principle detect; does anyone know of an existing tool that does so?</p>

<p>The second problem with the code is the re-use of the moved-from <code>p</code> â€“James correctly explains the problem. In order for the <code>std::move()</code> to have any effect, the argument to <code>add()</code> would need to be either a value or an r-value reference, for example:</p>

<pre class="programlisting">
  void add(std::string const &amp;name,
    programmer details)
  {
    team_.emplace(
      std::make_pair(name,
        std::move(details)));
  }</pre>
  
<p>(Note you also need to add <code>std::move()</code> when passing the <code>details</code> object to <code>emplace()</code>.)</p>

<p>However, it is still unspecified what the state of the object will be after the call, so it cannot be assumed to be empty.</p>

<h2>The Winner of CC 105</h2>

<p>After a full post-bag of six entries for CC104 I was disappointed to only receive one entry for CC105 â€“ but it was a clear and concise critique of the code and so I have no qualms in awarding James this issueâ€™s prize.</p>

<h2>Code Critique 106</h2>

<h3>(Submissions to scc@accu.org by Aug 1st)</h3>

<p class="blockquote">I am learning some C++ by writing a simple date class. The code compiles without warnings but Iâ€™ve made a mistake somewhere as the test program doesnâ€™t always produce what I expect.</p>

<pre class="programlisting">
    &gt; testdate
    Enter start date (YYYY-MM-DD): 2017-06-01
    Enter adjustment (YYYY-MM-DD): 0000-01-30
    Adjusted Date: 2017-07-31
    &gt;testdate
    Enter start date (YYYY-MM-DD): 2017-02-01
    Enter adjustment (YYYY-MM-DD): 0001-01-09
    Adjusted Date: 2018-03-10
    &gt;testdate
    Enter start date (YYYY-MM-DD): 2017-03-04
    Enter adjustment (YYYY-MM-DD): 0001-00-30
    Adjusted Date: 2017-04-03</pre>

<p class="blockquote">That last one ought to be 2018-04-04, but I canâ€™t see what Iâ€™m doing wrong.</p>

<p>Please can you help the programmer find his bug â€“ and suggest some possible improvements to the program!</p>

<ul>
	<li>Listing 4 contains <span class="filename">date.h</span></li>
	<li>Listing 5 contains <span class="filename">date.cpp</span></li>
	<li>Listing 6 contains <span class="filename">testdate.cpp</span></li>
</ul>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// A start of a basic date class in C++.
#pragma once

class Date
{
  int year;
  int month;
  int day;

public:
  void readDate();
  void printDate();
  void addDate(Date lhs, Date rhs);
  bool leapYear();
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &quot;date.h&quot;
#include &lt;iostream&gt;
using namespace std;

// Read using YYYY-MM-DD format
void Date::readDate()
{
  cin &gt;&gt; year;
  cin.get();
  cin &gt;&gt; month;
  cin.get();
  cin &gt;&gt; day;
}
// Print using YYYY-MM-DD format
void Date::printDate()
{
  cout &lt;&lt; &quot;Date: &quot; &lt;&lt; year &lt;&lt; '-' &lt;&lt;
    month/10 &lt;&lt; month%10 &lt;&lt; '-' &lt;&lt;
    day/10 &lt;&lt; day %10;
}

void Date::addDate(Date lhs, Date rhs)
{
  year = lhs.year + rhs.year;
  month = lhs.month + rhs.month;
  day = lhs.day + rhs.day;

  // first pass at the day -- no months
  // are over 31 days
  if (day &gt; 31)
  {
    day -= 31;
    month = month + 1;
    if (month &gt; 12)
    {
      year += 1;
      month -= 12;
    }
  }
  // normalise the month
  if (month &gt; 12)
  {
    year += 1;
    month -= 12;
  }
  // now check for the shorter months
  int days_in_month = 31;
  switch (month)
  {
  default: return; // done 31 earlier
  case 2: // Feb
    days_in_month = 28 + leapYear()?1:0; 
    break;
  case 4:  // Apr
  case 6:  // Jun
  case 9:  // Sep
  case 11: // Nov
    days_in_month = 30;
  }
  if (day &gt; days_in_month)
  {
    day -= days_in_month;
    month += 1;
    if (month &gt; 12)
    {
      month -= 12;
      year += 1;
    }
  }
}
bool Date::leapYear()
{
  // Every four years, or every four centuries
  if (year % 100 == 0) return year % 400 == 0;
  else return year % 4 == 0;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &quot;date.h&quot;
#include &lt;iostream&gt;

using std::cout;

int main()
{
  Date d1, d2, d3;
  cout &lt;&lt; &quot;Enter start date (YYYY-MM-DD): &quot;;
  d1.readDate();
  cout &lt;&lt; &quot;Enter adjustment (YYYY-MM-DD): &quot;;
  d2.readDate();

  // Add the two dates
  d3.addDate(d1, d2);
  cout &lt;&lt; &quot;Adjusted &quot;;
  d3.printDate();
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</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>
