Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you need to know about memory management in the simplest sense, is that you need to delete the memory that you allocate on the heap. So when creating an object like <code>MyClass *myClass = new MyClass(x);</code> you need to have some place in your code that frees/deletes this with a corresponding <code>delete</code>. This appears easy in practice, but without a proper design and the use of helper objects such as shared pointers, this can quickly get messy especially as code is maintained and features added. For example here is a classic memory leak:</p> <pre><code>try { MyClass *myClass = new MyClass(x); // Do some stuff can throw an exception delete myClass; } catch(...) { // Memory leak on exceptions. Delete is never called } </code></pre> <p>OR another big memory management gotcha is calling the wrong type of delete:</p> <pre><code>int* set = new int[100]; delete set; // Incorrect - Undefined behavior // delete [] set; is the proper way to delete an array of pointers </code></pre> <p>A common way to help yourself is to use the RAII idiom. (<a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow noreferrer">Resource Allocation Is Initialization</a>) </p> <p>Here is an example of using the std library in order to prevent a memory leak:</p> <pre><code>try { auto_ptr&lt;MyClass&gt; myClass(new MyClass(x)); // Now the heap allocated memory associated with myClass // will automatically be destroyed when it goes out of scope, // but you can use it much like a regular pointer myClass-&gt;memberFunction(); } catch (...) { } </code></pre> <p>More info on <code>auto_ptr</code> can be found <a href="http://en.cppreference.com/w/cpp/memory/auto_ptr" rel="nofollow noreferrer">here</a>. If you can use C++11, <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="nofollow noreferrer"><code>shared_ptr</code></a> is a highly recommended choice and is often preferred over auto_ptr.</p>
    singulars
    1. This table or related slice is empty.
    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.
    3. 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