Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

delete and delete[] — destroying dynamic objects

A delete expression destroys a single object created by new, while delete[] destroys an array created by new[]. Choosing the matching form is mandatory; mixing the forms causes undefined behavior.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

delete pointer;
delete[] pointer;

delete pointer destroys a single object created by new, while delete[] pointer destroys an array created by new[]. Both expressions have type void. In the ordinary case they invoke destructors and then release storage; array elements are destroyed in reverse order.

Do not confuse a delete expression with the deallocation function operator delete: the expression also handles object destruction. For arrays, the corresponding function is operator delete[]. The special destroying operator delete mechanism delegates destruction to the selected function.

Mismatching new/delete[] or new[]/delete, deleting a local object, and deleting the same object twice cause undefined behavior. With ordinary deallocation, deleting a single object through a pointer to a base class requires a virtual destructor in the base class only if the object's static and dynamic types are not similar. Do not delete arrays through a pointer to a base class.

If a well-formed delete or delete[] expression has a null pointer operand, C++23 leaves it unspecified whether the selected deallocation function is called. The deallocation functions provided by the standard library have no effect when called with a null pointer. That guarantee does not cover a class-specific deallocation function, which may not handle null safely.

delete does not set the pointer variable to nullptr. Explicit assignment after deletion changes only that variable, not other pointers to the deleted object.

Examples

#include <iostream>

struct Item {
    int id;
    ~Item() { std::cout << id << '\n'; }
};

int main() {
    Item* single = new Item{1};
    Item* array = new Item[2]{{2}, {3}};

    delete single;
    single = nullptr;
    delete[] array;
    array = nullptr;
    delete single;
}

Result

1
3
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version. The final `delete single` has a null pointer operand, but `Item` has no class-specific deallocation function.

Sources