Thursday, October 21, 2010

finally in C/C++

If you have programmed in C/ C++ you know there is no such thing as finally in C/C++. If you have used Java you know how convenient it is with finally to handle resources in code that is exception prone. There is a pretty nice and clean way to simulate finally in C++ (using destructors) but C doesn't have nice and clean way to do it. I am not sure if it is the recommended approach as it utilizes goto keyword. Since I started programming, I have been told not to use goto. Even while I read books i find authors ranting about use of goto. But here is a technique in C that simulates finally using goto.




void do_sth() {

int *arr1 = 0,*arr2 = 0, * arr3 = 0;

//calling function on will return error code, 0 being success
// and other values a failure
arr1 = (int *)malloc(100 * sizeof(int));
if(!arr1)
goto finally; // u wud have free(arr1) without finally

arr2 =(int*) malloc(100 * sizeof(int));

if(!arr2)
goto finally; //u wud have free(arr1) and free(arr2) without finally

arr3 =(int*) malloc(100 * sizeof(int));

if(!arr3)
goto finally; //u wud have free(arr1) and free(arr2) and free(arr3) without finally

//do sth here

finally:
free(arr1);
free(arr2);
free(arr3);
}



This is a simple example showing how you can handle exceptions in memory allocation. This makes sure that everything is freed when function exists and makes code lot cleaner. The resource allocation used here was simple. For example if you were opening 3 files instead. How would the code ? You would probably check if the file handle is valid in finally and if it is valid you would close them. The main advantage of this approach is that your resource handling code is localized. it's not spread over places and also you would write less code with this approach.

Now how would you do same thing in C++? Well C++ has facility for destructor which can do the job for you. When the object goes out of scope, the resource is cleaned up. There are lots of examples in C++ standard library. For example, instead of using dynamic arrays as shown above in C code, you could use std::vector in C++ which takes care of freeing the resources itself. Also there is std::auto_ptr which can be used for exception prone code. Of course auto_ptr doesn't support arrays.For supporting arrays you can use equivalent of boost's scoped_array.

No comments:

Post a Comment