This question may sound too simple to some guys, but I am trying to understand what happens if I delete an object having a dynamically allocated block using delete keyword
Calling a delete will do 2 things, first call the destructor and then release the memory.
If delete is releasing the object memory then will it also release the dynamic allocated memory or would I have to write a block of code in destructor to actually release the memory block safely.
Also if objects are allocated memory in heap then what other things other than member variables will take up the memory allocated to the object.
Thanks in advance
If you have something like this:
And subsequently do this:
Then yes, you’re leaking memory. The dynamic block in your Foo object is never released. You can address this with a destructor that releases it. (of source, you need to declare the destructor in the class declaration as well):
I would advise you to do two things
Following #2, btw, might give you an object that looks similar to this:
And a usage (one of many possibilities) like this:
Please regard the notes in the source of the last example. There is a tremendous weight lifted off your memory-management shoulders by using classes that practice self-managed members. In lifting that weight, so too goes the per-chance likelihood of introducing bugs related to it, like memory leaks, shallow-copy perils, etc.