Class destructors, and when to use them

1. Different sites seem to say different things about when a destructor should be created. I've read it's only necessary when you explicitly use the "new" keyword to create an object. Others say it's also needed whenever a pointer is created. Is it one, the other, or both?

2. If I don't explicitly create a destructor, the compiler creates a default one. Does this happen to include deletes for all of the class's objects, or is it empty and really doesn't do anything? I'm guessing it's empty, else why worry about creating one at all?

3. Say I write an app that has a class, and I don't write a destructor, and it causes a memory leak. Is that leak cleaned up when the app is closed, or does it remain in perpetuity, unavailable to the OS to reuse?
1. Strictly speaking, both are incorrect. Destructors need to be explicitly written when the class owns resources that not managed elsewhere and need to be released explicitly. Those resources may be memory, but they could also be file handles, network connections, concurrency locks, etc.

2. The compiler-generated destructor calls destructors for all members of the class. It's important to note that whether a destructor on a member is called depends on the type of the member, and not how the object in question was allocated. For example,
1
2
3
4
class A{
    int *foo;
    A(): foo(new int){}
};
Here, the compiler will not generate a destructor that does delete this->foo;. The compiler cannot keep track of raw pointer ownership for you. For example, it might be that you actually intended for another piece of code to release the pointer. If the compiler generated a delete in the destructor, that would break your code. If you use raw pointers you need to manage them yourself.
Don't use raw pointers, by the way.

3. The operating system is capable of reclaiming all memory from a process when that process terminates. This is something dangerous to rely on, however. For long-lived processes, memory leaks can be disastrous.
1. Closer to "both", but not really. See Rule of Zero in https://en.cppreference.com/w/cpp/language/rule_of_three

2. It is "empty body" but does not actually mean "doesn't do anything".

3. OS should be able to reclaim all memory when a process ends.
> Say I write an app that has a class, and I don't write a destructor, and it causes a memory leak.
> Is that leak cleaned up when the app is closed, or does it remain in perpetuity, unavailable to the OS to reuse?

Depends on the OS. Mainstream general purpose ones do clean up memory (and several other resources) when a user mode process exits.

OS in an embedded system (or the kernel, if the 'app' is a kernel mode component and has allocated kernel mode memory) may not do that; the memory may remain allocated till the OS is rebooted.
Topic archived. No new replies allowed.