Intro

RAII是c++的看手好戏,用过的都说好。面对c,可没有RAII这种东西使用。还好,gcc提供了一些折中的方案来剑走偏峰,来实现RAII。如下:

__attribute__((cleanup(free-function)))

attribute的使用简介还请看ref。此不在讲解范围内。

ref:
6.39 Attribute Syntax

具体用法

用这个实现自动回收str和tree;

/* Char Str free */
#define auto_sfree __attribute__ ((cleanup(sfree)))
#define auto_treefree __attribute__ ((cleanup(treefree)))
__attribute__((always_inline))
    inline void sfree(void* str) {
        if( !str ) return;
        free( *(void**)str );
    }
/* tree free */
__attribute__((always_inline))
    inline void treefree(void* tree) {
        if( !tree ) return;
        tree_free_por( *(treenode**)tree );
    }

usage:

int main(void) {
    auto_sfree tmp_str = calloc(100,1);
}
Smart Pointer in C

我们可以使用这个编译器提供的特性来实现一个c的smart pointer。

struct meta_data {
    void* data;
    int
}
Reference
  1. 6.39 Attribute Syntax
  2. Implementing smart pointers for the C programming language

更多文章请关注《万象专栏》