3 ms·
> In C++, the use of RAII means that exceptions can be made to free any dynamically allocated objects whose owners went out of scope as a result of the exceptio
by bluetomcat 10y ago
> In C++, the use of RAII means that exceptions can be made to free any dynamically allocated objects whose owners went out of scope as a result of the exception. In C, we don't easily have that option available to us, and those objects are just going to stay allocated.
In GCC and Clang, there is the "cleanup" attribute which runs a user-supplied function once a variable goes out of scope, so you can have scope-based destructors:
static void do_cleanup(char **str) {
free(*str);
}
void f(void) {
char *s __attribute__((__cleanup__(do_cleanup))) = malloc(20);
// s gets freed once the function exits
}
- pjmlp 10y agoWhich is inherently not portable across other C compilers.