Reputation: 738
I am not sure what exactly the command delete
does in c++? As far as I know, to free memory I have to use delete
on objects, that I previously instantiated with new
, like:
Obj* object = new Obj();
delete object;
But does delete
actually deletes data from my objects, does it in any way alter the object and data inside the object itself OR does it just call the corresponding destructor? If the destructor is empty, does useing delete
have any consequences to the object? The reason for this question is as follows:
If I just delete objects this way, the pointer gets invalid, and my program does crash. So, I think I should just call the destructor with the delete command and take further steps inside the destructor function do actually do the cleanup and to be sure that other objects refering to this object know that the pointer is truly invalid.
Upvotes: 3
Views: 863
Reputation: 223719
Besides calling the destructor, the delete
operator deallocates the memory that was previously allocated by new
. This memory goes back to the available pool of memory that can be allocated.
This also means that object
now points to invalid memory and any attempt to use it, or any other pointer that pointed to it, will invoke undefined behavior. This is probably what is happening in your program.
So your progam most likely has an issue with who "owns" the pointer. You shouldn't be calling delete
on a pointer value that is still being used elsewhere in your program.
Upvotes: 5