If you create an instance via new
:
MyClass *x = new MyClass();
you must delete it via delete
:
delete x;
1.) Call free(x);
No. free
only releases memory it does not call destructors. If you malloc
memory you need to free
it, but it is rare that you have to use malloc
in C++ and calling free
on a pointer obtained from new
is wrong.
2.) Call x->~MyClass();
No. Explicitly calling the destructor is almost always wrong!
(For example when you create an object via placement new then you don't call delete
but the destructor directly, because placement new creates the object in already allocated memory.)
3.) Call MyClass::~MyClass(p);
No. This makes no sense, destructors take no parameters.
4.) Call delete x;
Yes. Calling delete
...
Destroys object(s) previously allocated by the new expression and releases obtained memory area
But you should not manually manage memory. Either rely on automatic storage:
MyClass x;
The detructor of x
is called automatically when it goes out of scope. Or if you really need dynamic memory allocation use smart pointers.
For further reading: Why should C++ programmers minimize use of 'new'?
By the way, this is such a common misconception that each talk of Stroustrup i remember has an example that uses new
to create an object and then he explains that it should definitely not use new
. Actually there is more to it than forgetting to call delete
. Consider:
{
MyClass *x = new MyClass();
foo();
delete x; // phew I didnt forget to call delete
}
If foo
throws an exception then this code leaks memory. The right way is to rely on RAII:
{
MyClass x;
foo();
}
Now if foo
throws an exception, the destructor of x
will be called!