实施纯C RAII? [英] Implementing RAII in pure C?

查看:162
本文介绍了实施纯C RAII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能实现纯C RAII

Is it possible to implement RAII in pure C?

我想这是不可能的,任何理智的方式,但也许是有可能使用某种使坏的。重载标准的免费函数想到或者在栈上改写返回地址,以便当函数返回时,它会调用,不知怎的,释放资源,其他一些功能?或者,也许一些的setjmp / longjmp的把戏?

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?

这是一个纯粹的学术兴趣,我也没有实际编写这样的不可移植的疯狂code,但我想知道,如果这是在所有可能的意向。

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.

推荐答案

这是内在的依赖于实现,因为标准不包括这种可能性。对于GCC,当一个变量超出范围清除属性运行的函数:

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");
}

打印:

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

请参阅here

这篇关于实施纯C RAII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆