Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To a great extent, that's someone elevating their own weaknesses to a general rule. There's nothing wrong <em>per se</em> with creating objects using the <code>new</code> operator. What there is some argument for is that you have to do so with some discipline: if you create an object you need to make sure it's going to be destroyed.</p> <p>The easiest way of doing that is to create the object in automatic storage, so C++ knows to destroy it when it goes out of scope:</p> <pre><code> { File foo = File("foo.dat"); // do things } </code></pre> <p>Now, observe that when you fall off that block after the end-brace, <code>foo</code> is out of scope. C++ will call its dtor automatically for you. Unlike Java, you don't need to wait for the GC to find it. </p> <p>Had you written</p> <pre><code> { File * foo = new File("foo.dat"); </code></pre> <p>you would want to match it explicitly with</p> <pre><code> delete foo; } </code></pre> <p>or even better, allocate your <code>File *</code> as a "smart pointer". If you aren't careful about that it can lead to leaks.</p> <p>The answer itself makes the mistaken assumption that if you don't use <code>new</code> you don't allocate on the heap; in fact, in C++ you don't know that. At most, you know that a small amout of memory, say one pointer, is certainly allocated on the stack. However, consider if the implementation of File is something like</p> <pre><code> class File { private: FileImpl * fd; public: File(String fn){ fd = new FileImpl(fn);} </code></pre> <p>then <code>FileImpl</code> will <em>still</em> be allocated on the stack.</p> <p>And yes, you'd better be sure to have</p> <pre><code> ~File(){ delete fd ; } </code></pre> <p>in the class as well; without it, you'll leak memory from the heap even if you didn't <em>apparently</em> allocate on the heap at all.</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