Hi all,
I've created a class which uses the winapi. It has a number of constructors and a destructor. The class is called 'Thread'. When I use it like this:
Thread foobar(foobar, "foo", "bar");
it gives no problem. The class contains a handle of the thread. When the constructor is called it creates that handle and starts a new thread. To do that I use CreateThread from the winapi. The default constructor initializes the thread handle to 'INVALID_HANDLE_VALUE'. When the destructor is called, it uses CloseHandle to close the handle, but only if the handle doesn't equal to INVALID_HANDLE_VALUE. So what I believe should happen when you use it like this:
Thread test;
is that it creates no thread and on destruction, no handle gets closed.
However, when I do this:
1 2
|
Thread test;
test = Thread(foobar, "foo", "bar");
|
it runs the things in this order:
#1. It runs the default constructor.
#2. It runs the destructor with the three arguments.
#3. It runs the destructor, which I believe should be the dtor of the Thread created with the default constructor, but it contains the thread handle which is created by the ctor with the three arguments.
Then when they go out of scope:
#4. It calls the destructor with the same handle as in #3, so it closes that handle 2 times and that results in undefined behavior, in my case: an access violation error.
So my question is, why is the dtor of the same object called twice and the dtor of the 'empty' object none?