1. Computing & Technology

Discuss in my forum

Understanding Resource Acquisition is Initialization (RAII)

It's not just for C++

By , About.com Guide

RAII stands for Resource Acquisition Is Initialization. it's a useful way of handling resources, such as memory, fonts, files etc to ensure that they are released when no longer needed or when a process terminates due to an error. Resources are generally tied to objects. A file handling class will probably require a file handle to access a file, for opening, reading or writing the file etc. Once the object is finished with the file, the resource must be released.

The basic problem RAII solves is that if the file handling object terminates say due to an exception then the resource must be freed if it has been acquired. After an exception in C++, the only code that can run is the object's destructor. Constructor's can fail as well so it makes sense to return an exception.

This example, based on on in Wikipedia shows it in C++. The file class manages the file handle and relinquishes it in the destructor.

#include <cstdio>
#include <stdexcept> // std::runtime_error

class file {
public:
    file (const char* filename)
        : file_(std::fopen(filename, "w+")) {
        if (!file_) {
            throw std::runtime_error("file open failure") ;
        }
    }
 
    ~file() {
        if (std::fclose(file_)) {
// an error?
        }
    }
 
    void write (const char* str) {
        if (EOF == std::fputs(str, file_)) {
            throw std::runtime_error("file write failure") ;
        }
    }
 
private:
    std::FILE* file_;
 
    file (const file &) ;
    file & operator= (const file &) ;
};

int main(int arc,char * argv[]) {
    file logfile("c:\\fred.txt") ; //
    logfile.write("hello world!") ;
return 0;
}

RAII in C#

The using (... ) statement allocates resources and retains hold until it's exited. Behind the scenes it converts this into a try .. finally with a call to the Dispose() method. Using only applies to classes that descend from IDisposable.

using (var readStream = System.IO.File.OpenRead(f))
    {
        readStream.Read(buffer,0, buffer.Length);
    }

Conclusion

RAII is a straightforward concept. Only keep control of resources for the minimum time they are required and include code to manage them in case something goes wrong. This is perhaps one of the biggest differences between C and the other object oriented languages C++, C#. It takes a lot more code to do this in C.

©2012 About.com. All rights reserved.

A part of The New York Times Company.