C/C++ 中的 RAII

# RAII 的好处

* 异常安全
* 保证匹配
* 防止内存泄露

# RAII in C

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:

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

About 逸飞



电子邮件地址不会被公开。 必填项已用*标注