I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials.
Does any one have any nice links to teach me RAII?
I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials.
Does any one have any nice links to teach me RAII?
Item 13 of "Effective C+" is also pretty useful
There's nothing to it (that is, I don't think you need a full tutorial).
RAII can be shortly explained as "Every resource requiring cleanup should be given to an object's constructor."
In other words:
Pointers should be encapsulated in smart pointer classes (see std::auto_ptr, boost::shared_ptr and boost::scoped_ptr for examples).
Handles requiring cleanup should be encapsulated in classes that automatically free/release the handles upon destruction.
Synchronization should rely on releasing the mutex/synchronization primitive upon scope exit (see boost::mutex::scoped_lock usage for an example).
I don't think you can really have a tutorial on RAII (not anymore than you can have one on design patterns for example). RAII is more of a way of looking at resources than anything else.
For example, at the moment I'm coding using WinAPI and I wrote the following class:
This class doesn't include assignment and copy semantics (I removed them to provide a minimal example) so returning by value, will cause the handles to be closed twice.
Here's how it's used:
class declaration:
This member is allocated but I never call
::CloseWindow(_window._handle)
explicitely (it will be called when instances ofSomething
go out of scope (asSomething::~Something
->WindowHandle::WindowHandle
->::Close(_window._value)
).The wikipedia explanation isn't bad.
The reference that I personally have found most helpful on the topic of RAII is the book Exceptional C++ by Herb Sutter.
Many of the topics covered in that book are touched on in the Guru of the Week articles by Sutter. Those articles are available at http://gotw.ca/gotw/index.htm.