Modern Memory Management

Modern Memory Management

Replace manual ownership with RAII and smart pointers.

Modern Memory Management

Old style to avoid

Widget* widget = new Widget();
// ...
delete widget;

This style is error-prone because exceptions, multiple return paths, or missed deletes can leak memory.

Preferred style

auto widget = std::make_unique<Widget>();

The object is automatically destroyed when the owning smart pointer goes out of scope.

Shared ownership

Use std::shared_ptr only when several objects truly co-own the same resource.

Rule of thumb

Shared ownership pitfalls

Shared 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.

Views and borrowing

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.

Exception safety

RAII is what makes exception-safe code ordinary rather than special. Acquire resources into objects immediately so cleanup always happens on every path.