as I remember the ways (some of them)
(1)
Code:
#include <iostream>
using namespace std;
class Base
{ int* pBase;
public:
Base(){pBase=new int[8];cout<<"Base construCTOR"<<endl;}
virtual ~Base(){delete [] pBase; cout<<"Base destruCTOR"<<endl;}
};
class Derived : public Base
{ int* pDerived;
int ipd;
public:
Derived()
{ pDerived=new int[4096];
cout<<"Derived construCTOR pointer = "<<hex<<pDerived<<endl;
}
~Derived(){delete [] pDerived; cout<<"Derived destruCTOR"<<endl;}
};
void
main()
{ for(int i=0; i<4;i++)
{ Base* pB = new Derived;
delete pB;
}
}
To make the program fail, remove the virtual from the base class DTOR.
This exampled demos the concept
If the base class DTOR is virtual, the derived class DTOR will be called and memory allocated by the derived class will be released.
(2) If one stores pointers (created by new) in a container, one should perform a delete on the pointers after extraction (and final use) from the container. Then the rest of the pointers still in the container should be extracted and deleted.
(3) (mentioned above)the concept of a smart pointer is good because when the smart pointer goes out of scope (it is on the stack), its destructor is called and the memory allocation pointer is deleted.
(4) a new operation creates a pointer to memory and the pointer is passed to other methods. The general question is "who's responsibility is it to delete the pointer"
I have a vector program where ownership is decided at insert time. If the "vector" owns the pointers, it deletes the ones stored and the vector dies by going out of scope.
The example deletes the pointer and then allocates another chunk. If the new pointer is beyond the original, there is a memory leak.
(5) hmmm! what else???
If in doubt, add some cout statements and do the bookkeeping!
(6) I'll not mention the programming system but once I would pass on pointers and never get the chance to delete the pointers.
Tech support said "don't worry" SHUHR!