Memory Model
Understanding how C++ programs use memory is fundamental to writing efficient, safe code. Memory is divided into distinct regions with different characteristics and management strategies.
Storage Duration
Storage duration defines when and where objects are created and destroyed. C++ has four storage durations: automatic, static, dynamic, and thread.
Object Lifetime
Object lifetime spans from construction to destruction. Understanding lifetime is critical for memory safety, RAII, and avoiding undefined behavior.
Initialization
4 items
new & delete
Manual dynamic memory management in C++. Allocates on heap, requires explicit deallocation. Modern C++ prefers smart pointers.
Placement new
Constructs objects in pre-allocated memory without allocating. Separates construction from allocation for custom memory management.
Memory Alignment
Data arranged at addresses that are multiples of its size. Required for correctness on some architectures, critical for performance on all.
Strict Aliasing
Pointers of different types cannot point to the same memory (with exceptions). Enables compiler optimizations but causes undefined behavior when violated.