Resource acquisition is initialization in C lang

Question: Could you help me better understand the RAII macro in C (and not C ++) using only the resources that I will put at the bottom of this question? I am trying to analyze this in my mind in order to understand what he is saying and how it makes sense (it does not make sense in my mind). The syntax is complex. The focus of the question is: I have problems reading and understanding strange syntax and its implementation in C language. For example, I can easily read, understand and analyze (it makes sense for me) the following swap macro:

#define myswap(type,A,B) {type _z; _z = (A); (A) = (B); (B) = _z;} 

(The following passage is taken from the book: Understanding C-Pointers)

In C, the GNU compiler provides a custom extension for RAII support.

The GNU extension uses the RAII_VARIABLE macro. It declares a variable and is associated with a variable:

  • A type
  • Function executed when creating a variable
  • Function executed when a variable goes out of scope

    The macro is shown below:

    #define RAII_VARIABLE(vartype,varname,initval,dtor) \
    void _dtor_ ## varname (vartype * v) { dtor(*v); } \
    vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
    

    Example:

    void raiiExample() {
    RAII_VARIABLE(char*, name, (char*)malloc(32), free);
    strcpy(name,"RAII Example");
    printf("%s\n",name);
    } 
    
    int main(void){
        raiiExample();
    }
    

When this function is executed, the string "RAII_Example" is displayed. Similar results can be achieved without using the GNU extension.

+4
source share
3 answers

Ok, look at the macro parts along the line

#define RAII_VARIABLE(vartype,varname,initval,dtor) \

- , , . , , , , , - , , , , , . .

void _dtor_ ## varname (vartype * v) { dtor(*v); } \

. varname _dtor_ ( ## ). vartype .

(, ## , ), . :

vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)

​​, __attribute__() : vartype varname = (initvar). - __attribute__((cleanup(_dtor_ ## varname))). , , .


__attribute__() - , , , . , __attribute__((cleanup())). , . __attribute__(), #define __attribute__() , __attribute__() . , RAII. , __attribute__(), , .

+3

, - RAII. RAII , . :

void f() {
    char *v = malloc(...);
    // use v
    free v;
}

, , . ressources , RAII :

void f() {
    RAII_VARIABLE(char*, v, malloc(...), free);
    // use v
}

, ressource . , -, .., RAII ...

+2

, __attribute__ ((cleanup)) , . GCC ( ):

, . ( ) .

:

char *name __attribute__((cleanup(free))) = malloc(32);

, free name, char **. - , RAII_VARIABLE.

RAII_VARIABLE , raii_free:

#include <stdlib.h>

void raii_free(char **var) { free(*var); }

int main(void)
{
    char *name __attribute__((cleanup(raii_free))) = malloc(32);
    return 0;
}
+2

Source: https://habr.com/ru/post/1668745/


All Articles