Search code examples
c++pointersdelete-operator

Unclear about `delete` and pointers


Say we have a piece of code:

//...
class A
//...
A* myA = new A();
A* myPointerToMyA = myA;
delete myA;
delete myPointerToMyA; // this is wrong, no?
//...

The last line does the exact same thing as the one above it, correct? So I would now be deleteing an invalid/NULL pointer?

I understand this may be a stupid question, but still, I need some reassurance.


Solution

  • You are correct.

    So I would now be deleteing an invalid/NULL pointer?

    Well, technically it's only invalid, because nothing was set to NULL. It's ok to delete a NULL pointer.