RAII is a frequently used idiom in C++ that ensures the safe usage of resources by releasing them when an object's scope ends. In C++, resources allocated on the heap are not released unless explicitly done so, but those allocated on the stack are automatically released when their scope ends, triggering their destructor. Originally, RAII was used to guard against unexpected changes in control flow, such as exceptions.
In the above code example, the unsafeFunction()
function is not safe. If the thisFunctionCanThrowException()
throws an exception, the resource
may not be released. The unmaintanableFunction
releases the resource
, but it is not easy to read and maintain.
The safeFunction
example uses unique_ptr
, a smart pointer introduced at C++11, for RAII. unique_ptr automatically releases the memory it holds when it is destroyed, ensuring that the resource
is released when the function exits.
The resource
does not only refer to heap memory but also includes files, databases, and other things that can be safely used with RAII. Furthermore, RAII can be used to handle code that must always be executed when a specific scope ends, similar to the finally
statement in other languages. In fact, Bjarne Stroustrup, the creator of C++ and the term RAII, stated that there was no need for a finally
statement in C++ due to the existence of RAII.
This article is a translation of a Korean post written in 2014. If you would like to view the original, please refer to this link.
Comments
Post a Comment