shared pointers and RAII

I came upon a nice article on shared pointers: ONLamp.com — Smart Pointers in C++

It goes through auto_ptr, shared_ptr, shared_array and weak_ptr. Nice introduction, it has also a nice entry on RAII (more here).

Shared pointers make RAII really easy – for dynamic memory management, RAII can be applied to mutexes, files and many other kind of resources. Neat, really neat. I use this idiom a lot and it simplifies a *lot* code and resource management issues (posix locks, open files …).

The real goodies is that since in C++ destruction of objects is a deterministic operation (always called, never delayed), RAII when used with exceptions, let you use a “transactional” programming style:

In case of exceptions thrown, the RAII objects automatically get their destructors called and hence, acts like rollback operations when the destructor is called.

Advertisements

About this entry