Clarifying a Common Source of Pointer Confusion

Novices, especially those who have experience with garbage-collected languages, are often confused with the concept of object deallocation and destruction in C++. They tend to explicitly invoke every object's destructor or assume that every pointer must be deleted explicitly. However, in C++, there is a simple rule: only objects that were allocated by new must be destroyed using delete. When dealing with arrays allocated by new[], you must use delete[]. When shouldn't you use delete? First of all, when you have local automatic objects and static objects. These objects are destroyed automatically. Never attempt to destroy them explicitly. Furthermore, even if you have a pointer that is later assigned to an object, you shouldn't delete this pointer if its bound object wasn't allocated using new. Here's an example:

Because s is a local automatic object, you shouldn't delete the pointer ps. The bound object s will be destroyed automatically when f() exits. Remember that deleting any object that wasn't allocated using new causes undefined behavior (most likelya program crash).