C++ - new / delete

Overview

Estimated time: 30–40 minutes

Allocate objects dynamically with new/delete. Prefer RAII and smart pointers in modern C++.

Learning Objectives

  • Use new/delete and new[]/delete[] correctly.
  • Avoid leaks and double delete; prefer smart pointers.

Examples

int* p = new int(42);
int* a = new int[3]{1,2,3};
delete p; delete[] a;

Common Pitfalls

  • Mismatching new/delete[] calls; leak and undefined behavior risks.
  • Owning raw pointers without clear lifetime; use std::unique_ptr instead.