Tuesday 15 June 2010

c - Portable equivalent to gcc's __attribute__(cleanup) -


Recently I came across a GCC extension that I found to be useful: __feature__ (cleanup)

Basically, it allows you to allocate a squill call to a local variable, when this scope is released. For example, the following part of the code is given, within the call foo .

  void foo () should be maintained and maintained in all and all cases clearly in all cases {char * buff = ...; / * Some memory allocation * / char * buff2 = 0, * buff3 = 0; If (buff) {return; } Else {buff2 = ...; / * Memory allocation * / if (! Buff2) {geto clean_exit; } Else {/ * ... and so on ... *}} clean_exit: free (buff); Free (buff 2); Free (buff 3); }  

However,

  #define clean_pchar_scope __attribute __ ((cleaning (pchar_free) which can reduce the expansion) by using zero pchar_free ( Four ** c) {free (* c); } Void foo () {char * buff clean_pchar_scope = ...; / * Some memory allocation * / char * buff2 clean_pchar_scope = 0, * buff3 clean_pchar_scope = 0; If (buff) return; Buff2 = ...; / * Memory allocation * / if (! Buff2) return; / * And so on * /}  

Now all the memory has been retrieved on the basis of the scope without the use of the lower if / or or a concatenation of the Goto function release section Coupled together. I realize that the use of goto can be avoided for more nested if / other construction (then, please, there is no holy war on Goto ...) and that the example is hypothetical, but this is the fact That it can be quite useful feature

Unfortunately, as far as I know, this is GCC-specific. I'm interested in any portable way to do the same thing (if it exists). Do anyone have any experience in doing this besides GCC?

Edit: Keeping this in mind that portability is not in the game, is it a way to exit the GCC space? ? It seems that there is a special feature to be GCC-specific ...

No portable in C Not the way.

Fortunately, it is a standard feature of C ++ with Destructors.

Editing:

MSWC has __try and __finally keywords which can be used for this purpose. This is different from C ++ exception handling and I think is available in C.

I think that you feel that cleaning and try / end in particular, especially because of the underlying support in C ++, which is "close enough" for C, those who are interested in behavior Can easily convert your code to C ++.


No comments:

Post a Comment