June 14, 2006

Resource Acquisition Is Initialization

Filed under: commons, CPP

Software programs have to deal with resources (memory, files, mutexes, semaphores, database connections, …) that a computer provides. To be able to make sure that the resources are available to all the programs and optimally used, following steps are required to use a resource:

  • Acquire a resource
  • Use the resource
  • Release the resource

By acquiring and releasing the program stakes its claim to the resource. If the resource is not released it usually ends up causing memory leaks, deadlocks or sometimes crashes. Memory is the most commonly used resource and memory leaks are commonly witnessed. Resource Acquisition Is Initialization (RAII) is an idiom that provides a protocol for acquiring and releasing resources.

Encapsulates Allocation and Deallocation

The classes that are written usually provide a level of abstraction over the physical resources available. RAII allows us to encapsulate the acquisition and release of these resources. A popular example is that of using a database connection. If the connection is acquired from the connection pool and not released back, it finally runs out of the connections and applications cannot continue working with the database. This is more probable if you leave this responsibility to the user of your class (another programmer). Here is an example in C++, that uses RAII to acquire the connection and release it:

class MyRecords
{
    private:
       DBConn connection;
	
    public:
       MyRecords()
       {
           connection = new DBConn();
       }
	
       ~MyRecords()
       {
           delete connection ;
       }
}

When this class is used, it guarantees release of the connection when its destructor is called. The destructor can be explicitly called, but it is automatically invoked if it is used as a local variable and goes out of scope. Your user now does not need to worry about the database connection, nor do you have to worry if he/she has released the database connection which can lead to undersirable situations.

void useMyRecords()
{
    // Allocated on stack
    MyRecords records;
	
    ....
	
    // Will run out of scope beyond this method
}

The same can be applied to any resource that a program might work with.

Gives Control To You

RAII is just half the story, it also includes releasing the resource. For your user, the two different steps of initializing your object and acquiring the resource has been combined into one, in fact completely encapuslated. What this also means is that your user does not have to worry in unavoidable circumstances like exceptions. Stack variables automatically go out of scope and their destructors are invoked.

It is not always necessary to acquire a resource in the constructor, it might be done in any other intermediate methods. In this case, care should be taken to check if the resource acquisition was successful before releasing it.

Lesser and cleaner code is just one of the post-effects, the real benefit is that you, as owner of your class, get complete control of the resources that your class uses. This is exponentially beneficial if you author a library or a framework.

Where is it applicable?

RAII needs to be supported by a language to be used. Generally, a language which uses non-deterministic garbage collection, lika Java does not support RAII. If the language supports use of custom-defined types for local variables (automatic objects in C++), you can take advantage of the automatic invocation of destructors when they go out of scope. It is also supported by object models and languages like COM which relies on reference-counted garbage collection.

More reading:

Tags: , , , ,

June 7, 2006

Two Exceptional Conversations on C++

Filed under: CPP

I had come across two exceptional conversations on C++ between two visionaries - Bill Venners and Bjarne Stroustrup. They are dated 2003, but are very much valid even today.

Titled as The C++ Style Sweet Spot and Modern C++ Style, the discussions answer some principle questions about moving from C to C++, using inhertiance the right way, using abstract classes for interface and considering the invariant for designing simple classes. If you haven’t read them yet, jump right ahead and consume them, they provide lot of food for thought and can act as design guidelines.

Unique thing about reading the discussions was that Stroustrup has not given just point answers, but has explained the reasons behind the thoughts. I am sure such reading can lead to best practices.

Tags: , ,

May 29, 2006

C/C++ Cross Platform Libraries

Filed under: C, CPP

Developing cross-platform C/C++ code is not difficult, but definitely challenging and has to be disciplined. Usually, a separate interface is designed so that the platform-specific code is encapsulated. The challenges are presented on multiple fronts - every platform (OS and/or CPU architecture) has its own API for system operations, its own Endianness, implementation of pointers and more.

Today, developers have access to a plethora of cross-platform abstraction libraries. What this means is that the developers don’t have to worry about differences in the platforms and focus on their applications. The differences are abstracted into the libraries/toolkits/frameworks. Shlomi Fish has a nice extensive list including the popular Standard Template Library (STL).

Out of these, I have worked with Posix Threads for Win32, Boost and Mozilla XUL.

In addition to this Mozilla has a Cross Platform Component Object Model (XPCOM), which is the underlying base for every Mozilla application. I have also used Xerces C++ Parser. In addition to this, Ch language environment, an embeddable interpreter for cross-platform C/C++ scripting, is available for developing XML-based applications using C/C++..

Andrei Alexandrescu has developed a cross-platform library, called Loki (through his book Modern C++ Design), for illustrating benefits of policy-based programming. It employs template metaprogramming to the fullest.

Then there are Blitz++ and Matrix Template Library (MTL) (via O’Reilly Network).

As mentioned earlier, the code development should be disciplined to ensure portability. Mozilla has a C++ portability guide for making code portable.

I am sure all the libraries are not included here, if you know any that are not mentioned here, feel free to add them in the comments. I will update the post accordingly.

Tags: , , ,

May 26, 2006

C++ Techniques FAQ

Filed under: CPP

Bjarne Stroustrup answers some of the frequently asked questions regarding C++ style and techniques. However, this cannot replace books on C++; it is like an addendum to books.

It is a good revelation on some techniques, e.g., Should I use NULL or 0?” or So, what’s wrong with macros?. It also answers some design questions, e.g., about final keyword or pointers and references. However you should read Design and Evolution of C++ to understand the philosophy behind the C++ design.

These are not mandatory rules, just Stroustrup’s take on certain issues that can solve some everyday problems/doubts of a C++ programmer. And what better authority than the creator himself. Check it out!

Tags: , ,

Creative Commons License Copyright © Abhijit Nadgouda. Hosted on Blogsome, powered by Wordpress