Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The default destructor is destroying the pointer. If you want to delete the <code>N</code> with <code>M</code>'s default destructor, use a smart pointer. Change <code>N * n;</code> to <code>auto_ptr&lt;N&gt; n;</code> and <code>n</code> will be destroyed.</p> <p>Edit: As pointed out in comments, <code>auto_ptr&lt;&gt;</code> is not the best smart pointer for all uses, but it looks like what's called for here. It specifically represents ownership: the N in an M is there for the duration of the M and no longer. Copying or assigning an <code>auto_ptr&lt;&gt;</code> represents a change in ownership, which is usually not what you want. If you wanted to pass a pointer from M, you should pass a <code>N *</code> gotten from <code>n.get()</code>.</p> <p>A more general solution would be <code>boost::shared_ptr&lt;&gt;</code>, which will be in the C++0x standard. That can be used pretty much wherever a raw pointer would be used. It's not the most efficient construct, and has problems with circular references, but it's generally a safe construct.</p> <p>Another edit: To answer the question in another comment, the standard behavior of the default destructor is to destroy all data members and base classes. However, deleting a raw pointer simply removes the pointer, not what it points to. After all, the implementation can't know if that's the only pointer, or the important one, or anything like that. The idea behind smart pointers is that deleting a smart pointer will at least lead to the deletion of what it points to, which is usually the desired behavior.</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