I have some handle and I need to close it. There is some places in code, where handle may be closed. So, is this a right way to close handle?
HANDLE h;
....
if ( h != INVALID_HANDLE_VALUE ) {
::CloseHandle(h);
h = INVALID_HANDLE_VALUE;
}
There is a same question about bitmap handles:
HBITMAP hb;
....
if ( hb != INVALID_HANDLE_VALUE ) {
::DeleteObject(hb);
hb = INVALID_HANDLE_VALUE;
}
EDIT: I think, there is some misunderstanding. I know CloseHandle
is for closing handles. I'd like to know proper way for closing handles. A similar situations occurs with deleting of pointers.
Foo *foo = new Foo();
// for example there is 2 functions that can delete foo
void bar() {
....
delete foo;
}
void duck() {
....
delete foo;
}
So, the following code means problems:
bar();
duck();
There is some workaround for this case. We need to define bar
&duck
functions like this:
void bar() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
void duck() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
So we avoid repeated deleting of foo. The question is What is the proper way to close handles? I mean, How to avoid repeated closing handles problem?
CloseHandle
is indeed the correct function to call if you want to close a handle. But there are some exceptions, some functions create handles which should be closed differently. So either show us how the handle was created, or look it up yourself on MSDN :) – LacedaemonCloseHandle
, while other handles (usually GDI handles) have their own function. Still, on the MSDN page about the function used to acquire the handle is always listed the corresponding function to call to release it. – Ascomycete