Click to See Complete Forum and Search --> : The probelm with HANDLES


jweller
June 15th, 2004, 08:27 AM
I am constantly running into the following problem. Suppose I have a class with a HANDLE.

class T
{
HANDLE handle;

T()
T(const T & t)

~T ()
}

T::T()
{
handle = CreateEvent (NULL, TRUE, TRUE, NULL);
}

T::T(const T & t)
{
// What do you do here?

// Copy the handle from t?

handle = t.handle;

// Create a new handle?

handle = CreateEvent (NULL, TRUE, TRUE, NULL);

// Ideally, you assign the handle from t and increment the OS
// handle count. I don't see how you do this. Is there a way?

::DuplicateHandle () doesn;t seem to work
}


T:~:T()
{
CloseHandle (handle);
}

This problem is further compounded when using STL and you push the object into a container. You get temporarary copies, etc.

What can be done? I don't want event object I create to be on the heap.

Any ideas?

Thanks,
Jim

kuphryn
June 15th, 2004, 11:28 AM
First off, the HANDLE class member variable of class T is private. So first implement a member function that returns a copy of the HANDLE.

Kuphryn

jweller
June 15th, 2004, 01:08 PM
Ok fine. Make the handle member public.

This still does not solve the problem. When either of the objects goes out of scope, then destructor closes the event handle. The handle is closed therefore useless in the remaining object. This is what I am trying to get at.

I guess I will need allocate a wrapper class and reference count the HANDLE. Sure would be helpful, if the function DuplicateHandle () would bump and internal counter for us. That way the handle would remain valid until both objects went out of scope.

wezman2k
June 15th, 2004, 01:47 PM
when you write code, use the "code" button on the top of the message editor. that way you won't get smiles on accident or something when you post the message

souldog
June 16th, 2004, 12:54 AM
A class that wraps a handle is a perfect example of something that should not be copyable or assignable. So the answer to your
question is DONT implement operator= or the copy constructor.
in fact make them private and not implemented to enforce this.


What you should do is use reference counting like you have mentioned.
If the objects are used in the context of a single thread then
the smart pointer at www.boost.org will be perfect for this.


//edit
the exact link is
http://www.boost.org/libs/smart_ptr/shared_ptr.htm