C++ › Memory Management

What is RAII and how does it relate to memory management?

Intermediate

Answer

RAII (Resource Acquisition Is Initialization) ties a resource's lifetime to an object's lifetime: the resource is acquired in the constructor and released in the destructor. For memory, this means smart pointers or containers own heap memory and free it automatically when they go out of scope—even if an exception is thrown—eliminating manual delete and most leaks.
{
    auto p = std::make_unique<int>(5); // acquires
}   // destructor frees automatically
Real-world example Replacing raw new/delete with unique_ptr removes a whole class of leak and double-free bugs.

Common follow-ups: Why is RAII exception-safe? | What is the destructor's role?