EXT C++ Library - automatic

The ext::automatic is a templated wrapper used to bind a destruction function to a type.


The ext::automatic template can be used whenever you need to call a function when the variable gets out of a scope (is destroyed) and this cannot be achieved with destructor. For example when the variable is an intrinsic (int, float, ...) or you don't have control over the class.

This is particulary useful for handling operating system or C-like resource handles. One can simply wrap the handle into ext::automatic and not worry about releasing its data when it goes out of scope, thus causing resource leak. The provided destruction function is called in this case to release the resources.


template <typename T, void (F) (T &)>
class ext::automatic {
        typedef T type;

        automatic ();
        automatic (const T &);
        ~automatic ();

        operator       T & ();
        operator const T & () const;

              T * operator -> ();
        const T * operator -> () const;

        T & operator = (const T &);

template <typename T, void (F) (T &)>
bool operator == (const ext::automatic <T, F> &, const ext::automatic <T, F> &);

template <typename T, void (F) (T &)>
bool operator != (const ext::automatic <T, F> &, const ext::automatic <T, F> &);

The ext::automatic is a pointeresque type so the underlying object can be accessed by operator -> directly. The ext::automatic object also support implicit conversion to a reference to the wrapped type.


#include <ext/c++>
#include <windows.h>

void free_win32_handle (HANDLE & h) {
    CloseHandle (h);

int main () {
    ext::automatic <HANDLE, free_win32_handle> file = CreateFile (/* ... */);
    // the file handle is always closed when the control exits main


Particularly when the destruction function can throw an exception, note that it is called even when the wrapped object is destroyed during the stack unwinding (exiting the scope due to an exception being thrown). If another exception is thrown in that case, the std::terminate is called by C++ and the program is terminated.

You can use the std::pair or std::tr1::tupple to pack together more parameters for the destruction function.