Skip to content
UPEEC

RAII

Resource Acquisition Is Initialisation: tie every resource to an object's lifetime.

Intermediate
Comments 0

RAII means a resource (memory, file, mutex lock, interrupt disable) is acquired in a constructor and released in the destructor. Because destructors run automatically when objects leave scope — even during exceptions — leaks become almost impossible.

{
    std::lock_guard<std::mutex> lock(m);   // locks
    shared_counter++;
}                                          // unlocks automatically

Embedded example: a CriticalSection object that disables interrupts in its constructor and re-enables them in its destructor.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.