I’ve been told that when if I have multiple pointers pointing to the same object, I cannot delete it normally (using the delete keyword). Instead, I’ve been told that I need to set the pointers to NULL or 0.
Given I have:
ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* pointer2 = object;
So to delete pointer1 and pointer2, do I need to do the following?
pointer1 = 0;
pointer2 = 0:
Once I’ve set it to NULL, do I still need to use the keyword delete? Or is just setting it to 0 good enough?
Whenever you
newan object, you need todeleteit, free’ing the memoryThe point of setting your pointers to
NULLis to stop dereferencing pointers that are invalidThis is done so that tests can be performed before attempting a dereference:
Also note that you can delete the memory from any pointer that points to it.
object, pointer1, and pointer2now all point to memory that has already been released, and unless they will be redefined, they should all be set to NULL.