When the object a is destroyed, is the personsInHouse map also destroyed or I need to destroy it in destructor? Will it create memory leak if I don’t?
class A {
public:
map<unsigned int, unsigned int> personsInHouse;
};
int main(){
A a;
A.hash[10] = 23;
};
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:
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
then
pis the only member ofS, and whenSgoes out of scope,pwill be destroyed (which doesn’t generally involve anything happening, except perhaps an adjustment of the stack pointer). If you at some point doS s; s.p = new int;thenpwill still be the only member, and the object pointed to bypwill not be one, and will therefore not be destroyed whensgoes out of scope. For that to happen, you will need to manually dodelete s.p;, which corresponds to the general rule of everynewneeding to have a correspondingdelete(idem fornew[]anddelete[]).