new and delete
new T allocates storage and constructs a T. delete p destroys the object and frees the storage. new T[n] and delete[] p are the array forms. Prefer std::make_unique over bare new in application code.
Detailed Explanation
new is two steps: allocate raw memory (as if operator new(sizeof(T))), then construct T in that memory. If the constructor throws, the memory is freed and the exception propagates. You never see a pointer to an unconstructed T from an ordinary new.
delete p is the reverse: run ~T, then operator delete. delete nullptr is a no-op. delete of a pointer that was not returned by new, or delete twice, is undefined behaviour.
Arrays: new T[n] constructs n elements and may store a cookie so delete[] knows n. Mixing delete with new[] (or the reverse) is undefined. You almost never write new[]. std::vector<T> is the array.
new (std::nothrow) T returns nullptr on allocation failure instead of throwing std::bad_alloc. The constructor can still throw. Check the pointer.
new can be overloaded per class (operator new / operator delete members) for arenas and pooling. Global replaceable operator new is how sanitizers and debug heaps hook allocation. Placement new is a different feature: construct in existing storage, no allocate.
Why not write new in application code: every new needs a matching delete on every path. Exceptions, early returns, and extra aliases make that a leak or a double-free. unique_ptr is the matching delete. make_unique is the matching new. The pair is then exception-safe.
A base pointer to a derived object needs a virtual destructor, or delete skips the derived destructor.
malloc/free do not run constructors or destructors. Do not delete a malloc pointer. Do not free a new pointer. std::malloc is for C APIs and byte buffers you will placement-new into.
Code Examples
#include <iostream>
#include <memory>
int main() {
auto p = std::make_unique<int>(7); // new + owning pointer
std::cout << *p << '\n'; // prints: 7
} // delete runs here#include <new>
#include <iostream>
int main() {
int* p = new (std::nothrow) int(3);
if (!p) return 1;
std::cout << *p << '\n'; // prints: 3
delete p;
}Common Gotchas
`delete` versus `delete[]`
mismatch is UB. Use `vector`.
Double `delete`
set the pointer to `nullptr` after `delete` if it lives on, or do not use a raw owning pointer.
`new` of an array of a type without a default constructor
`new T[n]` needs `T()`. Use `vector` and `push_back`.
`delete p` when `p` is a base pointer
without a virtual destructor, derived cleanup is skipped.