Modern Memory Management
Modern Memory Management
Replace manual ownership with RAII and smart pointers.
Modern Memory Management
Replace manual ownership with RAII and smart pointers.
Widget* widget = new Widget();
// ...
delete widget;
This style is error-prone because exceptions, multiple return paths, or missed deletes can leak memory.
auto widget = std::make_unique<Widget>();
The object is automatically destroyed when the owning smart pointer goes out of scope.
Use std::shared_ptr only when several objects truly co-own the same resource.
std::unique_ptr secondstd::shared_ptr only when requiredShared ownership can hide lifetime relationships. It also introduces atomic reference counting overhead and can create cycles.
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev;
};
Use std::weak_ptr to break cycles in graph-like structures.
Owning types manage lifetime. Borrowing types such as std::span and std::string_view only observe data. This distinction is one of the most important modern C++ habits to internalize.
RAII is what makes exception-safe code ordinary rather than special. Acquire resources into objects immediately so cleanup always happens on every path.