Unusual RAII from LibVLC

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Fri
27
Jan 2012

RAII (Resource Acquisition Is Intialization) is a programming technique recommended in C++ for managing and freeing all kinds of resources, like allocated memory or opened files. It involves creating on the stack (by value) an object of some class that will automatically free contained resources in its destructor, at the end of the scope. That's how smart pointers work. Using it is not only needed for exception safety. It generally helps not to forget about freeing resources, like when doing return or break in the middle of the code, as well as not to duplicate this freeing code.

When working with LibVLC library, I've spotted an interesting RAII-like pattern in its source code. It is based on a local structure inside a function, which holds resources and frees in its destructor these resources that are already acquired - like this:

bool DoLotsOfStuff()
{
    struct Resources
    {
        int* array;
        FILE* file;

        ~Resources()
        {
            if( file )
                fclose( file );
            if( array )
                delete[] array;
        }
    } resources = { 0 };

    // Do some startup...

    if( CheckSomeError() )
        return false;

    resources.array = new int[1024];

    // Do some work...

    if( CheckSomeError() )
        return false;

    resources.file = fopen( fileName, "rb" );
    if( resources.file == NULL )
        return false;

    // Do some more work...

    if( CheckSomeError() )
        return false;

    // array is freed and file is closed no matter if control reached here or returned earlier.
    
    return true;
}

Comments | #c++ Share

Comments

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2019