http://www.asawicki.info/ Graphics programming, game programming, C++, games, Windows, Internet and more... |
|
19:01
Fri
27
Jan 2012
Unusual RAII from LibVLC
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 (4) | Tags: c++
|
Xion 2012-01-27 19:55:54 | That's not only uglier than vector and ifstream, but also more verbose and error-prone. I hope you intended it only as a bad example :) |
|
Liosan 2012-01-28 08:32:35 | @Xion I understand it was meant to be an example of RAII in pure C... |
|
Reg 2012-01-28 11:13:45 | Liosan: Pure C doesn't have destructors, just like any methods in classes or structures :) |
|
Liosan 2012-01-28 22:31:48 | duh, facepalm... :) I looked up LibVLC and saw it was a C library, guess I got suggested :) |
| [Stat] [Admin] [STAT NO AD] [pub] [Mirror] | Copyright © 2004-2012 Adam Sawicki |