Resource acquisition is initialization: Difference between revisions

Content deleted Content added
External links: {{C++ programming language}}
Don't use a macro in compiler "cleanup" extensions - adds indirection not required to understand the concept
Line 116:
| work=Using the GNU Compiler Collection (GCC)
| publisher=[[GNU Project]]
| access-date=2019-03-09}}</ref> The following [[macro (computer science)|macro]] annotates a variable with a given destructor function that it will call when the variable goes out of scope:
 
<syntaxhighlight lang=c>
static inline void fclosep(FILE **fp) { if (*fp) fclose(*fp); }
#define _cleanup_fclose_ __attribute__((cleanup(fclosep)))
</syntaxhighlight>
 
This macro can then be used as follows:
<syntaxhighlight lang=c>
void example_usage() {
_cleanup_fclose___attribute__((cleanup(fclosep))) FILE *logfile = fopen("logfile.txt", "w+");
fputs("hello logfile!", logfile);
}