>>17
that's some pretty cool stuff bro. It reminds me of the c implementations of stack based language/virtua machine. You could implement dynamic scoping with something like that if you wanted to.
It might be possible with macros though, which would be ideal since the destructor calls could be determined at compile time. It would be trivial to do in lisp, and lisp weenies do it all the time with stuff like with-open-file. Here's an attempt with the C preprocessor:
#include <stdio.h>
#include <malloc.h>
#define SCOPE(type, variable_name, constructor_expression, destructor_expression, body) \
{ \
type variable_name = constructor_expression; \
body \
destructor_expression; \
}
int main(int argc, char** argv) {
SCOPE(int*, x, malloc(sizeof(int)), free(x),
*x = 5;
printf("[%p] = %d\n", x, *x);
)
return 0;
}
$ a.out
[0x8dfc008] = 5
$ valgrind --leak-check=full a.out
==2702== Memcheck, a memory error detector
==2702== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2702== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info
==2702== Command: a.out
==2702==
[0x4181028] = 5
==2702==
==2702== HEAP SUMMARY:
==2702== in use at exit: 0 bytes in 0 blocks
==2702== total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==2702==
==2702== All heap blocks were freed -- no leaks are possible
==2702==
==2702== For counts of detected and suppressed errors, rerun with: -v
==2702== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 13 from 8)
$