DevAcademia lesson/C++ Basics
new and delete
Topic progressTopic 66 of 109 - 61% complete
~5 min lesson21 learning blocks2 code examples1 checks/interactions
Lesson outline
Basic new and delete Usage
The new operator allocates memory on the heap and returns a pointer to it. The delete operator deallocates memory previously allocated by new.
Key points:
newcalls constructors for objects and (by default) throwsstd::bad_allocon failuredeletecalls destructors for objects- Each
newmust be paired with exactly onedelete(andnew[]withdelete[]) - Using
deleteon memory not allocated withnew(or mixingnew/delete[]) causes undefined behavior
Syntax Examples
Initialization Forms
Fundamental types are uninitialized with new T but value-initialized to zero with new T() or new T{}:
int* p1 = new int; // indeterminate valueint* p2 = new int(); // 0int* p3 = new int{}; // 0
Advanced new/delete Features
Placement new: Constructs an object in pre-allocated memory
nothrow new: Returns nullptr instead of throwing on failure
Alignment-aware allocation (C++17): Request specific alignment
Overloading operator new/delete: Custom allocation strategies
Best Practices
- Prefer stack allocation where possible
- Always match
newwithdeleteandnew[]withdelete[] - Prefer smart pointers (
std::unique_ptr,std::shared_ptr) for automatic cleanup - Prefer standard containers (
std::vector,std::string) over raw arrays - Initialize memory after allocation (or use value-initialization
new T{}) - Reset pointers to
nullptrafter deletion to avoid dangling pointers
Common Pitfalls
- Mixing
newwithdelete[]ornew[]withdelete(UB) - Double-delete or deleting stack memory (UB)
- Forgetting to
delete[]arrays (leaks) - Assuming
new Tzero-initializes fundamental types (it does not) - Holding raw pointers across ownership boundaries; prefer RAII
Was this topic clear?