Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing RAII in pure C?

Tags:

c

raii

Is it possible to implement RAII in pure C?

I assume it isn't possible in any sane way, but perhaps is it possible using some kind of dirty trick. Overloading the standard free function comes to mind or perhaps overwriting the return address on the stack so that when the function returns, it calls some other function that somehow releases resources? Or maybe with some setjmp/longjmp trick?

This is of a purely academic interest and I have no intention of actually writing such unportable and crazy code but I'm wondering if that is at all possible.

like image 703
elifiner Avatar asked Dec 15 '08 13:12

elifiner


1 Answers

This is inherent implementation dependent, since the Standard doesn't include such a possibility. For GCC, the cleanup attribute runs a function when a variable goes out of scope:

#include <stdio.h>  void scoped(int * pvariable) {     printf("variable (%d) goes out of scope\n", *pvariable); }  int main(void) {     printf("before scope\n");     {         int watched __attribute__((cleanup (scoped)));         watched = 42;     }     printf("after scope\n"); } 

Prints:

before scope variable (42) goes out of scope after scope 

See here

like image 74
Johannes Schaub - litb Avatar answered Nov 05 '22 04:11

Johannes Schaub - litb