C++ Flashcards: Memory Management
C++ — Memory Management Flashcards
20 interactive flashcards. Press Space to flip, rate 1-4 to schedule next review.
Intuition
RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime, when an object is constructed it acquires a resource (memory, file handle, mutex lock), and when it goes out of scope its destructor releases it automatically. Smart pointers (std::unique_ptr, std::shared_ptr) extend this to heap memory: unique_ptr is exclusive ownership (like a single key to a safe), while shared_ptr is shared ownership with reference counting (like a library book with multiple borrowers).
Common Pitfalls
- Raw new/delete: Using
newanddeletemanually instead of smart pointers, this is the most common source of memory leaks and double-free bugs in C++. - Circular references with shared_ptr: Two objects holding
shared_ptrto each other create a reference count cycle that never reaches zero, usestd::weak_ptrto break the cycle. - Dangling pointers: Holding a raw pointer or reference to an object that has been destroyed, prefer smart pointers and avoid raw pointer ownership.
Cross-References
- Object-Oriented Programming: OOP patterns that rely on proper resource management.
- Error Handling: Exception safety and error handling with RAII.
- Types: Type system concepts including smart pointer types and ownership semantics.