Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Do as follows:</p> <pre><code>#include &lt;cstddef&gt; template &lt;typename T&gt; class Array { public: T* const arrayPointer; // arrayPointer can't be reallocated const size_t size; // size can't change Array(const int theSize) : arrayPointer(new T[theSize]), size(theSize) {} ~Array() { delete[] arrayPointer; } private: Array(const Array&amp; other) {} // forbid copy Array&amp; operator= (const Array&amp; other) {} // forbid assignment } ; </code></pre> <ul> <li>Why to use <code>template &lt;typename T&gt;</code>? So you can have an array of any type.</li> <li>Why to use <code>new T[ theSize ]</code> ? So you can allocate <code>theSize</code> elements at the same time.</li> <li>Why to use <code>: arrayPointer( new T[ theSize ])</code> ? So in case allocation fails (due to big theSize) the object fails without initialization. It is callled RAII.</li> <li>Why to use <code>delete [] arrayPointer</code> ? Because you used <code>new[]</code> and you have to deallocate the whole array.</li> <li>Why those <code>const</code>'s? To avoid anyone changing the size of the array and making the fields inconsistent.</li> <li>What are these private methods? They are forbiding copies, so no one can make <code>array1 = array2; delete array2;</code>, what would deallocate the arrayPointer of array1.</li> </ul> <p>Usage (it will allocate array of 10 int:)</p> <pre><code>Array&lt; int &gt; arr( 10 ) ; </code></pre> <p>Access:</p> <pre><code>arr.arrayPointer[ 0 ] = 5 ; </code></pre> <p>Note - you can access <code>arrayPointer</code> at the cells of range 0..9. You can add <code>operator[]</code> to your class in order to avoid using <code>arrayPointer</code> and to use <code>arr[ 0 ]</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload