Destructor for class without dynamically allocated memory

How does the destructor for a class without dynamically allocated objects look? I know the compiler makes one by default, and I never bother with it if I don't allocate memory myself.

If there is nothing to do, then there is nothing to do.
1
2
3
MyClass::~MyClass()
{
}

Note: Some versions of pimpl idiom do require explicit constructor outside of class definition (not in the header) even though the constructor does nothing (explicitly).
Destructors are not just for releasing memory. As keskiverto implies, they're for doing whatever needs to be done when an object goes away. Here are some examples of things I've done with destructors:

Closed files.
Released mutexes.
Logged output.
Participated in memory use analysis.
Stopped timers.

There are so many more. Effectively infinite, I expect. I would anticipate that as you begin to internalise C++ classes into your thinking, you'll start designing your classes such that they have things to do at destruction. If that never happens, you're missing something in your thinking.
Thanks!

what happens with the memory when you don't explicitly release it though? Who releases it, if the destructor is "empty"?
Release what memory?

1
2
3
void dummy() {
  int victim;
}

There was memory allocated from stack for the automatic variable 'victim'.
The "destructor" of an int is "empty", isn't it?
Yet, stack unwinding does release the memory at end of the function call.

1
2
3
4
5
6
7
8
class Raw {
  double left;
  int right;
};

void dummy() {
  Raw victim;
}

It is still the stack unwinding that releases the memory that was allocated for victim.
The member variables were within that memory.

1
2
3
4
5
6
7
8
class Raw {
  std::vector<double> left;
  Raw() : left(42) {}
};

void dummy() {
  Raw victim;
}

Still the same story. However, the constructor of victim did make the 'left' allocate memory for 42 doubles (dynamically).

The destructor of Raw has no explicit statements, but it does call the destructor of member 'left' that does call destructors of the 42 doubles (which is trivial), and then deallocates the dynamic memory block that the array did occupy.


Class destructor (even the default version) does call the destructors of the member variables and then the destructors of base class(es) after the body of the destructor.
Topic archived. No new replies allowed.