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