I thought it was a good idea to use this in my C++ projects:
class CRAIICall
{
public:
typedef void (WINAPI * FnType)(HANDLE);
CRAIICall(HANDLE h, FnType fun)
: m_h(h), m_fun(fun)
{}
~CRAIICall() {
if (m_h) { m_fun(m_h); }
}
private:
HANDLE m_h;
FnType m_fun;
};
and use it like this in a function:
HMODULE hSrClient = ::LoadLibraryW(L"srclient.dll");
CRAIICall(hSrClient, (CRAIICall::FnType)::FreeLibrary);
so that I can simply return from my function at any point, or throw exceptions.
Is it safe to cast a function pointer like this?
Other comments about this code are also appreciated.