The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can’t manage to achieve that.
I have this:
class N {
public:
~N() {
std::cout << "Destroying object of type N";
}
};
class M {
public:
M() {
n = new N;
}
// ~M() { //this should happen by default
// delete n;
// }
private:
N* n;
};
Then this should print the given message, but it doesn’t:
M* m = new M();
delete m; //this should invoke the default destructor
What makes you think the object
npoints to should be deleted by default? The default destructor destroys the pointer, not what it’s pointing to.Edit: I’ll see if I can make this a little more clear.
If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed?
The
tpointer is cleaned up, but theThingit points to is not. This is a leak. Essentially the same thing is happening in your class.