What is RAII and how does it relate to memory management?
Short 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.
Advertisement
AModel 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 automaticallyReal-world example
Replacing raw new/delete with unique_ptr removes a whole class of leak and double-free bugs.
Likely follow-ups
- Why is RAII exception-safe? | What is the destructor's role?
Related topics