    <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  :: Some Thoughts on the Use of New</title>
        <link>https://members.accu.org/index.php/articles/1355</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 #2 - Jun 1993</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/c222/">02</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+222/">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;Some Thoughts on the Use of New</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 30 June 1993 11:56:00 +01:00 or Wed, 30 June 1993 11:56:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p>One of the reasons some C++ programmers like to use new to create
objects is that the memory required for the object is taken from the
heap rather than the stack. In many environments stack space is limited
and needs to be carefully nursed. This is certainly the case with PC's
running MSDOS. The problem becomes more severe if you are using a
recursive algorithm as part of your problem solution.</p>
<p>The problem with the standard (as found in most books) method of
using new to create objects is that an explicit pointer is used to
handle the object. This raises two problems. First you will often have
to specifically dereference a pointer. The second problem is that you
can re-assign the pointer without using delete to release storage back
to the heap.</p>
<p>Of course neither problem is fundamental but both add to the
potential for making mistakes. For example consider the following
minimalist program:</p>
<pre class="programlisting">#include &lt;iostream.h&gt; <br>main()<br>{<br>  int * a = new int(23);<br>  cout&lt;&lt;a&lt;&lt;endl; // value of a intended<br>  return 0; <br>}</pre>
<p>A simple coding error that will be easily identified in this
context. In many other cases the type checking built into the compiler
will trap errors caused by failure to dereference a pointer. But what
happens if you use a cast, perhaps to resolve an overload ambiguity as
in the following code.</p>
<pre class="programlisting">#include &lt;iostream.h&gt;<br>void fn(char c) { cout&lt;&lt;c&lt;&lt;endl; }<br>void fn(long l) { cout&lt;&lt;l&lt;&lt;endl; }<br>main()<br>{<br>  int a = 23;<br>  fn(a);<br>  return 0; <br>}</pre>
<p>If you try to compile this code you will get an ambiguity error. You
can fix that by changing the call to:</p>
<pre class="programlisting">fn((char) a)</pre>
<p>To make your intentions explicit. So far so good, but look what
happens when we decide to use new to create storage (Yes, I know this
is silly when dealing with builtins but I do not want to have to
implement a user defined type, where its size might make such methods
desirable).</p>
<p>The code now reads as:</p>
<pre class="programlisting">#include &lt;iostream.h&gt;<br>void fn(char c){ cout&lt;&lt;c&lt;&lt;endl; }<br>void fn(long l){ cout&lt;&lt;l&lt;&lt;endl; }<br>main()<br>{<br>  int * a = new int(23);<br>  fn((char)a);<br>  return 0; <br>}</pre>
<p>The cast now does two things, what we wanted -resolving the
ambiguity - and something we did not want - casting a pointer to an int.</p>
<p>Furthermore none of the uses of new above have been matched with
delete. Careless, but it also allows this to happen:</p>
<pre class="programlisting">main()<br>{<br>  int * a = new int(23);<br>  fn((char)a);<br>  a=new int[24];<br>  return 0; <br>}</pre>
<p>Again this is simply bad programming and in some instances you might
turn on the programmer and blame his lack of care. However it might be
better to show how</p>
<p>a different approach might eliminate much of the problem. Consider
replacing</p>
<pre class="programlisting">int * a = new int(23);</pre>
<p>with</p>
<pre class="programlisting">int &amp; a = *new int(23);</pre>
<p>That simple change removes the danger of casting a pointer into
something else that you did not intend. It also allows the compiler to
detect any attempts to re-use the id to point at something else. We are
still left with a couple of problems. The first is the need to match
uses of new with uses of delete. The line</p>
<pre class="programlisting">delete a;</pre>
<p>generates an error (just as well, else this method would be far too
dangerous) but</p>
<pre class="programlisting">delete &amp;a;</pre>
<p>does exactly what we want. Perhaps you wish that when an object is
created via this route that it will automatically be destroyed when the
reference variable goes out of scope. A little careful thought should
convince you that, even if implementors could write compilers that
could recognise this method, it would be intolerable to implement such
an idea. Would you and the compiler always agree? No, the simple rule
is best -every use of new requires an explicit corresponding use of
delete.</p>
<h2>How to Deal with Arrays</h2>
<p>Unfortunately the way that C (and hence C++) implements arrays means
that we cannot use the above method for them. However if we understand
the C implementation of an array we can duplicate it for a dynamic
array and gain reasonable security. C treats an array name as if it was
a * const T type. That is a constant pointer to type T.</p>
<p>So what we need is code like:</p>
<pre class="programlisting">#include &lt;iostream.h&gt;<br>void fn(char c){ cout&lt;&lt;c&lt;&lt;endl; }<br>void fn(long l){ cout&lt;&lt;l&lt;&lt;endl; }<br>main()<br>{<br>  int * const a = new int[23];<br>  for(int i=0;i&lt;23;i++) a[i]=i;<br>  fn((long)a[20]);<br>  delete [] a;<br>  return 0; <br>}</pre>
<p>Once again we get the advantage of automatic dereferencing (i.e. the
code we write for our dynamic array is indistinguishable from that used
with a static one). Be careful to get the const in the right place when
dealing with multi-dimensioned arrays. Well that is only a tiny part of
the problem. When dealing with such objects you should certainly create
an appropriate class. Try it without! Remember that C++ provides you
more powerful tools, if you insist you can use an ordinary screwdriver
on a machine screw.</p>
<h2>And Finally</h2>
<p>The use of reference variables in a class has some interesting
consequences which certainly require some careful writing of copy
constructors and destructors. More particularly it introduces some
problems with writing overloads for assignment operators. It torpedoes
the default operator=. I think that is beneficial, but others will
disagree.</p>
<p>If Mike is agreeable I will write next time about the use of new in
class definitions and how to minimise stack use when implementing
recursive algorithms.</p>
<p style="font-style: italic;">I am always agreeable to you writing for
Overload <br>
Francis.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
