Yes, it is. When the destructor of a class is run, the destructors of all its members are run. To be precise, the order is:
- Body of the destructor is run
- All members, in reverse order of construction, are destructed
- All non-virtual base classes, in reverse order of construction, are destructed
- All virtual base classes, in reverse order of construction, are destructed
In general, if you don't have pointers, you can expect to also not have memory leaks. This is not always the case: you may be using a leaky function, or some function may be performing dynamic allocation and then returning a reference to the object. The situation can be further improved by using smart pointers.
A useful technique for avoiding memory leaks in C++ is RAII: all standard containers follow it, which is why there's no need to explicitly clear()
a container before it goes out of scope. The basic principle is to make classes clean up all their resources in their destructors, and then make dedicated classes for that so that most of your classes need not worry about it.
Do note that "class members" are strictly non-static members defined at class scope. If you have
struct S {
int* p;
};
then p
is the only member of S
, and when S
goes out of scope, p
will be destroyed (which doesn't generally involve anything happening, except perhaps an adjustment of the stack pointer). If you at some point do S s; s.p = new int;
then p
will still be the only member, and the object pointed to by p
will not be one, and will therefore not be destroyed when s
goes out of scope. For that to happen, you will need to manually do delete s.p;
, which corresponds to the general rule of every new
needing to have a corresponding delete
(idem for new[]
and delete[]
).