Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>My thought process is that I'm using a <code>Set *aSet = new Set;</code> in my main class and since an int is not an object, it's not being freed when I call list.clear(). Is this right? How would I go about deleting the memory correctly?</p> </blockquote> <p>No. To delete the memory you allocate correctly you need to call delete:</p> <pre><code>Set *aSet = new Set; delete aSet; </code></pre> <p>However manually managing memory like this is difficult and error prone. You should prefer alternatives. The first is that you should not use dynamic allocation at all. You should simply use automatic variables:</p> <pre><code>Set aSet; // no delete required. Variable destroyed/deallocated when it goes out of scope. </code></pre> <p>If you really do need dynamic allocation you should use smart pointers.</p> <pre><code>std::unique_ptr&lt;Set&gt; aSet(new aSet); </code></pre> <p>Smart pointers implement RAII for dynamic allocation so you don't have to do it manually.</p> <p>In some rare circumstances you may actually need to do dynamic allocation manually, but that's an advance topic.</p> <hr> <p><code>std::vector&lt;T&gt;::clear()</code> is not required to deallocate the vector's memory. You can use the C++11 member function <code>shrink_to_fit()</code>, or you can use the swap trick:</p> <pre><code>std::vector&lt;int&gt; list; ... std::vector&lt;int&gt;(list).swap(list); </code></pre> <p>Also you really shouldn't be using a pointer to a vector. A vector uses RAII to manage dynamic memory for you. When you use a pointer to a vector you no longer have the benefit of not manually managing the resource yourself.</p>
 

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