On this page
new & delete
Prev: sizeof & alignof | Up: builtins | Next: C++ Named Casts
Rel: std::unique_ptr, std::make_unique, RAII, Smart Pointers & Lifetime
Ref: cppreference — new expression
Tags: #public #prog #cpp #builtins #memory #tier/specialized
Overview
new allocates dynamic memory and constructs an object; delete runs the destructor and frees the memory (new[] / delete[] for arrays). In modern C++, avoid raw owning new and delete in application code—prefer std::make_unique, std::make_shared, or standard containers like std::vector.
When Raw new Still Appears
- Implementing low-level custom allocators or arena pools using placement
new:new (buf) MyType(args...)(which constructs in pre-allocated storage without allocating). - Interfacing with legacy C++ APIs that transfer raw owning pointers (wrap immediately in a
std::unique_ptr).
Pitfalls
- Mismatching
new[]with scalardelete(ormallocwithdelete) is undefined behavior. - Any exception thrown between
newanddeleteleaks the allocation unless owned by an RAII handle.
Linked from
Related notes
- tuts/cpp/builtins/sizeof_and_alignof Linked here; links to this page; shared tags: #builtins, #cpp, #memory, #prog, #tier
- tuts/cpp/builtins/casts Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/stdlib/memory/make_unique Linked here; links to this page; shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime Linked here; shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/stdlib/memory/unique_ptr Linked here; shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/stdlib/containers/vector Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/auto shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier