7. {
string device_name(“Large Hadron Collider”);
DeviceCloser dc(device_name);
dc.start();
// … Whatever happens here, the device will be closed
// and the world will be saved
} // Device closed here
9. // in the the C language, see."cleanup" variable attribute”
#define RAII_VARIABLE(vartype,varname,initval,dtor)
void _dtor_ ## varname (vartype * v) { dtor(*v); }
vartype varname __attribute__((cleanup(_dtor_ ##
varname))) = (initval)
// This macro can then be used as follows:
void example_usage() {
RAII_VARIABLE(FILE*, logfile, fopen("logfile.txt", "w+"),
fclose);
fputs("hello logfile!", logfile);
}
11. Things to Remember
• To prevent resource leaks, use RAII objects
that acquire resources in their constructors
and release them in their destructors.
• Commonly useful RAII classes are
shared_ptr,auto_ptr, etc[code] (another
seminar)
12. List of references:
• Scott Meyers, Effective C++: 55 Specific Ways
to Improve Your Programs and Designs
• Stephen C. Dewhurst, C++ Common
Knowledge: Essential Intermediate
Programming
• Matthew Wilson, Imperfect C++: Practical
Solutions for Real-Life Programming