So to understand new/delete better (really to prove to myself with small examples why virtual destructors are needed for interfaces), I want to understand memory leaks, so that I may live in fear of them. But I am having a hard time getting my leak on, so to speak; actually, I am have a hard time with new/delete too.
Here's my simplest version:
int* P1 = new int(43);
cout << "P1 = " << P1 << endl;
cout << "*P1 = " << *P1 << endl;
delete P1;
cout << "P1 = " << P1 << endl;
cout << "*P1 = " << *P1 << endl;
This prints:
P1 = 0xcc0340
*P1 = 43
P1 = 0xcc0340
*P1 = 43
I had something more complicated inside of a class, but this example illustrates my fail. I thought delete takes a pointer and frees it's memory, thereby invalidating the pointer or at least what it points to? I must be doing something very simple very wrong.
delete pointer
means "delete the object pointed to by the pointer". It does not mean "delete the pointer". – DigestantNULL
), and if it remains in scope after it has been deleted, it is good practice to do so. – Agata