RAII & Smart Pointers

Dec 4, 2025 · C++

RAII (Resource Acquisition Is Initialization) is a core C++ pattern for deterministic resource management. Wrap resources in types whose destructors release them.

unique_ptr

Use `std::unique_ptr` for exclusive ownership. It is lightweight and clearly expresses intent.

std::unique_ptr<MyType> ptr = std::make_unique<MyType>(args);

shared_ptr

Use `std::shared_ptr` only when shared ownership is necessary. Prefer `weak_ptr` to break cycles.

Custom RAII types

For resources other than memory (file descriptors, locks), create small RAII wrappers that implement move-only semantics where appropriate.