Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.</p> <pre><code>class A { char *someHeapMemory; public: A() : someHeapMemory(new char[1000]) {} ~A() { delete[] someHeapMemory; } }; class B { A* APtr; public: B() : APtr(new A()) {} ~B() { delete APtr; } }; class C { A Amember; public: C() : Amember() {} ~C() {} // A is freed / destructed automatically. }; int main() { B* BPtr = new B(); delete BPtr; // Calls ~B() which calls ~A() C *CPtr = new C(); delete CPtr; B b; C c; } // b and c are freed/destructed automatically </code></pre> <p>In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.</p> <p><code>auto_ptr</code>, <code>unique_ptr</code> and <code>shared_ptr</code> etc... are great for making this lifetime management much easier:</p> <pre><code>class A { shared_array&lt;char&gt; someHeapMemory; public: A() : someHeapMemory(new char[1000]) {} ~A() { } // someHeapMemory is delete[]d automatically }; class B { shared_ptr&lt;A&gt; APtr; public: B() : APtr(new A()) {} ~B() { } // APtr is deleted automatically }; int main() { shared_ptr&lt;B&gt; BPtr = new B(); } // BPtr is deleted automatically </code></pre>
    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. 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.
    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