CurriculumRAII Concept

RAII Concept

RAII stands for <strong>Resource Acquisition Is Initialization</strong>. It is the most important design pattern in C++. It means that the lifecycle of a 'Resource' (like heap memory, a file handle, or a network socket) is exactly tied to the lifecycle of a stack object.

01The Manual Way (Dangerous)

Look at this manual memory management. If an error occurs halfway through, the function returns early and the delete is skipped! We just leaked memory.
main.cpp
Loading...
Terminal
Waiting for execution...

02The RAII Way (Safe)

Now we wrap the pointer in a class. The Constructor acquires it. The Destructor releases it.

Even though we return early, C++ guarantees that the destructor of wrapper will run as it gets popped off the stack!
main.cpp
Loading...
Terminal
Waiting for execution...

03Standard Library RAII

You don't have to write these wrappers yourself. The C++ Standard Library provides them for you!

std::vector is just an RAII wrapper around a dynamic array. std::unique_ptr is an RAII wrapper around a single pointer.
main.cpp
Loading...
Terminal
Waiting for execution...
← Back to Curriculum