Re: Dealing with HANDLEs



I agree. It is coherent with the fact, that, if the class is really a
"ProcessInformation" class, there is no need for it to hold a handle to
the process as a data member (the handle should be opened just when
needed, in order to call APIs, then closed immediatly).

I disagree with both of you. There is nothing intrinsically wrong or harmful
with copying a handle. In practice some minimal caution needs to be
exercised but this is easy enough. As you stated, it should also be opened
and closed at the earliest opportunity so the underlying object can be
removed as soon as possible (depending on who else holds a handle to the
object at the time). This applies to all resources however. In practice,
copying a handle is actually a rare occurence. Where it really comes into
play in the real world (typically) is when you've encapsulated a handle in a
class and then need to copy that object (the subject of this post). Maybe
you have an STL collection of those objects and by definition those objects
must have proper copy semantics (although typically you'll have collections
of pointers to support polymorphic behaviour). Caching of the handle may
also be necessary for performance or other reasons. A blanket statement that
the encapsulated handle shouldn't be duplicated (by privatizing the copy
constructor and copy assignment operator) means that you can't copy your own
object. This is completely unreasonable IMO and normally unecessary.
Programmers should exercise good judgment and caution at all times (a rarity
in real life) but I've been using my own HANDLE wrapper for many years and
have never had any issue (and I've been in the coding trenches longer than
most).


.


Loading