Scope Gaurd for win32 API like closehandle
Problem:
Often when writing win32 APIs I need a way to automatically call CloseHandle() for mutex, semaphore, events etc. But the problem writing a code for win32 API is there is not mechanism for automatically calling CloseHandle() function when the scope of the function or class member exits. We have to keep track of return statements and call CloseHandle() in all place we need.
E.g:
void SomeOperation()
{
WaitforSingleObject(hMutex, INFINITE);
if(do_operation1() != ERROR_SUCCESS)
{
std::cout << "Error operation 1"<<endl;
CloseHandle(hMutex);
return;
}
if(do_operation2() != ERROR_SUCCESS)
{
std::cout << "Error operation 2"<<endl;
CloseHandle(hMutex);
return;
}
//success so close it normally
CloseHandle(hMutex);
return;
}
So I define my own macro to do this operation using std::bind and class template.
#define SCOPED(fun,param)\
auto f = std::bind(fun, param);\
Scoped<decltype(f)> obj(f);
template <typename func>
class Scoped
{
private:
func f;
public:
Scoped(func& temp) :f(temp) {}
~Scoped()
{
cout << "Called scoped destructor";
f();
}
};
So the operation become simple now I dont have to call CloseHandle() is all return statements. This is what I do. It automatically takes care of calling the CloseHandle() when ever the function exits.
void SomeOperation()
{
WaitforSingleObject(hMutex, INFINITE);
SCOPED(CloseHandle, hMutex);
if(do_operation1() != ERROR_SUCCESS)
{
std::cout << "Error operation 1"<<endl;
return;
}
if(do_operation2() != ERROR_SUCCESS)
{
std::cout << "Error operation 2"<<endl;
return;
}
return;
}
Comments
Post a Comment