Raii Idiom
Table of Contents


Resource Acquision Is Initialization, is a programming idiom.

In C++ the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack. So, resources need to be tied to the lifespan of suitable objects in order to gain automatic reclamation.


The following RAII class is a lightweight wrapper of the C standard library file system calls. [1]

#include <cstdio>
#include <stdexcept> // std::runtime_error
class file {
    file (const char* filename)
        : file_(std::fopen(filename, "w+")) {
        if (!file_) {
            throw std::runtime_error("file open failure");
    ~file() {
        if (std::fclose(file_)) {
           // failed to flush latest changes.
           // handle it
    void write (const char* str) {
        if (EOF == std::fputs(str, file_)) {
            throw std::runtime_error("file write failure");
    std::FILE* file_;
    // prevent copying and assignment; not implemented
    file (const file &);
    file & operator= (const file &);

Use of class file

void example_usage() {
    file logfile("logfile.txt"); // open file (acquire resource)
    logfile.write("hello logfile!");
    // continue using logfile ...
    // throw exceptions or return without
    //  worrying about closing the log;
    // it is closed automatically when
    // logfile goes out of scope

When file objects are local to a function, C++ guarantees that they are destroyed at the end of the enclosing scope (the function in the example), and the file destructor releases the file by calling std::fclose(file_).

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.