C/C++ 中的 RAII

Author: yifei / Created: May 29, 2017, 11:36 p.m. / Modified: May 29, 2017, 11:37 p.m. / Edit

RAII 的好处


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

有任何问题可以发邮件到 kongyifei (at) gmail.com 讨论