RAII

Kyuwon Kim
Dec 29, 2021

Resource Acquisition Is Initialization

RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection — anything that exists in limited supply) to the lifetime of an object.

from https://en.cppreference.com/w/cpp/language/raii

RAII는 SCP나 YAGNI 와 같은 코딩을 위한 규칙이나 원칙(Principle)이 아닌 C++에서 다음과 같이 초기화를 통해서 자원을 얻고 해당 블록이 종료되면 자동으로 자원을 해제하는 기법(Technique)이다.

void raii_example()
{
std::lock_guard<std::mutex> lock(m); // RAII class: mutex acquisition is initialization
f(); // if f() throws an exception, the mutex is released
if(!everything_ok()) return; // early return, the mutex is released
}

--

--