One solution for translating RAII to C (when you don't have cleanup() ) is to enclose the function call in code that will do the cleanup. It can also be packaged in a neat macro (shown at the end).
void SomeFunction() { Raii raii; RaiiCreate(&raii); SomeFunctionImpl(&raii); RaiiDestroyAll(&raii); } void SomeFunctionImpl(Raii *raii) { MyStruct *object; MyStruct *eventually_destroyed_object; int *pretend_value; object = RaiiAdd(raii, MyStructCreate(), MyStructDestroy); eventually_destroyed_object = RaiiAdd(raii, MyStructCreate(), MyStructDestroy); pretend_value = RaiiAdd(raii, malloc(sizeof(int)), 0); RaiiDestroy(raii, eventually_destroyed_object); RaiiForgetAbout(raii, eventually_destroyed_object); }
You can express all boiler panel code in SomeFunction using macros, because it will be the same for every call.
For example:
/* Declares Matrix * MatrixMultiply(Matrix * first, Matrix * second, Network * network) */ RTN_RAII(Matrix *, MatrixMultiply, Matrix *, first, Matrix *, second, Network *, network, { Processor *processor = RaiiAdd(raii, ProcessorCreate(), ProcessorDestroy); Matrix *result = MatrixCreate(); processor->multiply(result, first, second); return processor; }); void SomeOtherCode(...) { /* ... */ Matrix * result = MatrixMultiply(first, second, network); /* ... */ }
Note: you would like to use an extended macro structure such as P99 to make something like the above described possible.
Keldon Alleyne Jun 07 '13 at 21:43 2013-06-07 21:43
source share