C++C++ Explainer
C++ · 3 · Memory & Smart Pointers12 / 36 · 33%

new, delete & Why You Should Avoid Them

The raw layer under smart pointers — know it, then stop writing it.

Examples: new, delete[], leaks, make_unique

shortcuts: ← prev · → next · M mark
1

Raw Allocation

new calls the constructor; delete calls the destructor.

Example
example
Widget* w = new Widget(42);
delete w;

int* arr = new int[100];
delete[] arr;          // [] form is mandatory for arrays
STACKautomaticfast, LIFOsmall (~1 MB)frees on returnHEAPmanual / newlargelifetime = youfree / delete
objects on the heap outlive their scope
2

malloc vs new

They are not interchangeable.

malloc / free
aspectbehaviour
ctor/dtornot called
returnvoid*
failurereturns NULL
sizeyou compute it
→
new / delete
aspectbehaviour
ctor/dtorcalled
returntyped pointer
failurethrows bad_alloc
sizededuced
Never free() something from new, or delete something from malloc().
3

The Leak Paths

Any early return or throw between new and delete leaks.

Example
example
void bad() {
    Widget* w = new Widget;
    if (!validate()) return;   // LEAK
    risky();                   // throws -> LEAK
    delete w;
}

void good() {
    auto w = std::make_unique<Widget>();  // always freed
}
4

Modern Guidance

Almost no application code should contain new or delete.

TIP
Prefer a value member, then std::vector/std::string, then make_unique, then make_shared. Raw new belongs inside library internals only.