3 ms·
RAII is just automation and semantic sugar for something like this (or the equivalent set of goto labels that do the freeing at the end of the function): {
by yason 2y ago
RAII is just automation and semantic sugar for something like this (or the equivalent set of goto labels that do the freeing at the end of the function):
{
void *buffer = malloc(SIZE_MAX);
if (buffer) {
if (!do_stuff(buffer)) {
free(buffer);
return;
}
more_stuff(buffer);
free(buffer);
}
return;
}
If you wanted something like that in C it doesn't need to emulate C++ style RAII with classes and strongly typed constructors. It could look like something like, for example, where you just define pairs of allocator and free functions:
allocdef void *autobuffer(malloc, free);
...
{
autobuffer buffer(SIZE_MAX);
if (buffer) {
if (do_stuff(buffer)) {
return;
}
more_stuff(buffer);
}
return;
}
The implementation would effectively be a Lisp style macro expansion encoded in the C compiler (or preprocessor) that would just basically write out the equivalent of the first listing above.
- Mesopropithecus 2y agoIn the second example, buffer is still a pointer? If so, when does free run, and who decides that? When buffer goes out of scope, could do_stuff store the pointer some place else? I find this an interesting thought experiment, basically types that you'd opt in to RAII. Just have a feeling that you'll need to define some notion of ownership to make it work.