Alex Rivera | Logout

Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)

Asked 2009-04-03T05:21:53.390
121

Could you C++ developers please give us a good description of what RAII is, why it is important, and whether or not it might have any relevance to other languages?

I do know a little bit. I believe it stands for "Resource Acquisition is Initialization". However, that name doesn't jive with my (possibly incorrect) understanding of what RAII is: I get the impression that RAII is a way of initializing objects on the stack such that, when those variables go out of scope, the destructors will automatically be called causing the resources to be cleaned up.

So why isn't that called "using the stack to trigger cleanup" (UTSTTC:)? How do you get from there to "RAII"?

And how can you make something on the stack that will cause the cleanup of something that lives on the heap? Also, are there cases where you can't use RAII? Do you ever find yourself wishing for garbage collection? At least a garbage collector you could use for some objects while letting others be managed?

Thanks.

Edit
Report

1 Answer

11

RAII is using C++ destructors semantics to manage resources. For example, consider a smart pointer. You have a parameterized constructor of the pointer that initializes this pointer with the adress of object. You allocate a pointer on stack:

SmartPointer pointer( new ObjectClass() );

When the smart pointer goes out of scope the destructor of the pointer class deletes the connected object. The pointer is stack-allocated and the object - heap-allocated.

There are certain cases when RAII doesn't help. For example, if you use reference-counting smart pointers (like boost::shared_ptr) and create a graph-like structure with a cycle you risk facing a memory leak because the objects in a cycle will prevent each other from being released. Garbage collection would help against this.

answered 2009-04-03T05:28:39.507

Your Answer