CKTIS / C++
Array `new[]` and `delete[]` vs. single-object forms
Use `delete` for an object created with `new T` and `delete[]` for an array created with `new T[n]`. These expressions manage object lifetimes; the corresponding `operator new` and `operator delete` functions, with or without `[]`, manage storage.
Version: ISO C++23; implementation support may vary
Syntax
T* one = new T{};
delete one;
T* many = new T[n]{};
delete[] many;
// Representative global storage-function declarations from <new>:
void* operator new(std::size_t bytes);
void* operator new[](std::size_t bytes);
void operator delete(void* storage) noexcept;
void operator delete[](void* storage) noexcept;Curriculum scope: The operator.new and operator.delete cards must explicitly cover the array forms new[] and delete[] and distinguish them from the single-object forms. In C++23, new T{} creates and initializes one object, while new T[n]{} creates an array and initializes its elements. Both return T*, so the pointer type alone does not tell you which delete expression to use. An array still requires delete[] when n is 0 or 1.
delete p destroys a single object; delete[] p destroys the array elements from last to first. Storage is then released. Do not swap the forms: a mismatch is undefined behavior, even for int. Pass delete[] the original pointer value returned by the array new-expression, not a pointer advanced into the array. A null pointer is valid for either form and destroys nothing.
operator new and operator delete name the single-object storage functions; operator new[] and operator delete[] name their array counterparts. A direct call is not the same as an expression: ::operator new[](bytes) takes a byte count and does not call T constructors, while ::operator delete[](raw) releases a matching storage block without calling element destructors. An array new-expression may request extra bytes, and the pointer it returns may differ from the storage block's address.
Global functions have overloads that take an alignment argument, and global deallocation functions also have overloads that take a size. Classes can define their own functions; ::new or ::delete[] restricts lookup for the relevant function to global scope. With ordinary throwing global allocation, storage exhaustion is reported by std::bad_alloc; an invalid runtime array length, such as a negative count, can result in std::bad_array_new_length.
Examples
#include <cstdio>
struct Item {
int id;
~Item() { std::printf("destroy %d\n", id); }
};
int main() {
Item* one = new Item{0};
delete one;
Item* many = new Item[2]{{1}, {2}};
delete[] many;
}Result
destroy 0 destroy 2 destroy 1
`delete one` prints `destroy 0`. Then `delete[] many` destroys the element at index 1 before the element at index 0, printing `destroy 2` and `destroy 1`. The `id` values are not array indices.
Related lessons
- C++ · Lesson 57 · Intermediate · Version: 2