At the moment I'm on Windows and I work with WinAPI. I do not like try\catch so I use RAII, and this is construction which I usually use:
#define r_free(N, T, F, n) \
struct N { \
T res; \
N() : res(NULL) {} \
~N() { if (res) F(res); } \
} n
This macro allows me to write code such as below:
r_free(Hndl, HANDLE, ::CloseHandle, f);
DWORD err;
if(INVALID_HANDLE_VALUE == (f.res = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISING, 0, NULL))) {
err = GetLastError();
std::cout << err << std::endl;
return err;
}
It works fine but not all WinAPI functions (which are required to free resourses) take one parameter. Maybe there is a way to edit macro above to fix this issue? What is better way to do this?