Memory and Resource Management in C++
Ownership, lifetimes, allocation and move semantics. Smart pointers and RAII have their own pages earlier in this subject.
This is an overview — pick a sub-topic below.
Sub-topics (14)
Pointers in C++
Raw pointers still exist, but in modern C++ they mean "non-owning observer".
unique_ptr
Sole ownership of a heap object; deleted automatically, movable but not copyable.
shared_ptr
Shared ownership with reference counting; the object dies when the last owner goes.
weak_ptr
A non-owning reference to a `shared_ptr` object that can check whether it's still alive.
Dynamic Allocation in C++
Objects created at run time on the free store.
new and delete
Allocate and construct / destroy and deallocate objects.
Memory Alignment in C++
`alignof`, `alignas` and `std::aligned_alloc` control object alignment.
Object Lifetime
When an object begins and ends — and rules about using it outside that window.
Placement new
Construct an object in memory you already have: `new (buffer) T(args)`.
Allocators
Objects that supply memory to containers.
Custom Memory Pools
Pre-allocate blocks of fixed-size objects for fast, fragmentation-free allocation.
Move Semantics
Transfer ownership of resources from temporaries instead of copying them.
Perfect Forwarding
Pass arguments through a template keeping their value category, using `T&&` + `std::forward<T>`.
Rule of Zero, Three and Five
If a class manages a resource, define all special members (Five); better, let members manage it and define none (Zero).
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.