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 arraysobjects on the heap outlive their scope
2
malloc vs new
They are not interchangeable.
malloc / free
| aspect | behaviour |
|---|---|
| ctor/dtor | not called |
| return | void* |
| failure | returns NULL |
| size | you compute it |
new / delete
| aspect | behaviour |
|---|---|
| ctor/dtor | called |
| return | typed pointer |
| failure | throws bad_alloc |
| size | deduced |
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.