If you delete an object, the destructor for that object will be called, so you need to do a delete in the destructor. So remember, everything that the class has allocated on the heap has to be freed in the destructor. If it was been allocated on the stack this happens automatically
struct A
{
A() { std::cout << "A()" << std::endl; ptr = new char[10]; }
~A() { std::cout << "~A()" << std::endl; delete []ptr; }
char *ptr;
};
But be careful, if you are using inheritance, if A
inherits from a base class, you need to make the base destructor virtual, or else the destructor in A
will not be called and you will have a memory leak.
struct Base
{
virtual ~Base() {}
};
struct A : public Base
{
A() { std::cout << "A()" << std::endl; ptr = new char[10]; }
~A() { std::cout << "~A()" << std::endl; delete []ptr; }
char *ptr;
};