Related topic
std::unique_ptr, deleters and the Win32 API
To use a Win32 Handle as a RAII, I can use the following line
std:
I often use this in C++11:
#include
namespace{
template
struct RAII_Helper{
template
RAII_Helper(InitFunction &&init, F &&exit) : f_(std::forward(exit)), canceled(false){
init();
}
RAII_Helper(F &&f) : f_(f), canceled(false){
}
~RAII_Helper(){
if (!canceled)
f_();
}
void cancel(){
canceled = true;
}
private:
F f_;
bool canceled;
};
}
template
RAII_Helper RAII_do(F &&f){
return RAII_Helper(std::forward(f));
}
template
RAII_Helper RAII_do(Init &&init, Exit &&exit){
return RAII_Helper(std::forward(init), std::forward(exit));
}
usage:
FILE *f = fopen("file", "r");
if (!f)
return "error";
auto filecloser = RAII_do([=]{fclose(f);});
//also makes for good init / exit objects
static auto initExit = RAII_do([]{initializeLibrary();}, []{exitLibrary();});
I like it because it works for arbitrary code, not just pointers or handles. Also the cancel function could be omitted if never used.