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 with new
that you own. In this very case it looks like class A
owns that very instance of class B
and is responsible for calling delete
.
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 in class A
to prevent shallow copying the object which will cause you much trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With