I have the following code and I'm wondering if that delete b
is necessary here ?
Will my operating system automatically clear that area of memory allocated ?
class A
{
B *b;
A()
{
b = new B();
}
~A()
{
delete b;
}
};
Many thanks.
Yes, you have to
delete
every object created withnew
that you own. In this very case it looks likeclass A
owns that very instance ofclass B
and is responsible for callingdelete
.You'll be much better off using a smart pointer for managing
class B
instance lifetime. Also note that you have to either implement or prohibit assignment operator and copy constructor inclass A
to prevent shallow copying the object which will cause you much trouble.Resource management is more than just deallocating memory. Yes, most platforms will make any memory you allocate when the process ends, and memory is cheap enough that maybe you won't notice for a while. But what about the file
b
is holding open, or the mutex it will unlock in its destructor? Well before you run out of memory, you can encounter issues from letting your objects live past their usefullness.It will clear the area only when the process ends, but the area will remain allocated all the time until then, which means memory leak.