< All Topics

RAII (Resource Acquisition Is Initialization)

Type: C++ Coding Pattern

This is a fancy term for a simple rule: “If you pick it up, you must put it down automatically.”

In C++, if you manually allocate memory (the Heap) using new, you must remember to delete it. If you forget, you get a memory leak. Humans always forget.

RAII solves this. It ties the life of the memory to the “Scope” (the curly braces { }).

  • The “Constructor” (Birth) acquires the resource.
  • The “Destructor” (Death) releases the resource.

The Hotel Key Analogy:

  • Manual C++: You walk into a hotel room, turn on the lights. When you leave, you must flip the switch off. If you forget, the lights stay on forever (Memory Leak).
  • RAII: The hotel room requires your Key Card to turn on the lights. You stick the card in (Constructor). When you leave, you take your card out, and the lights automatically turn off (Destructor). You cannot forget.

Unreal Example:

  • Bad (Manual): Enemy* e = new Enemy(); (If the function crashes before you delete e, memory is leaked).
  • Good (RAII): TUniquePtr<Enemy> e = MakeUnique<Enemy>(); (When the function ends, e is automatically deleted from memory).

RAII: Coding style to prevent memory leaks.