I would like to know is this is possible. Create a shared_ptr or unique_ptr of TestClass type.
Then call _beginthreadex and pass it a static method of the class as the function to execute and the shared_ptr or unique_ptr created before as data. Like this:
shared_ptr<TestClass> p = make_shared<TestClass>(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);
I normally use this approach without smart pointers, I usually create a normal pointer of TestClass and pass a static method of the TestClass and the pointer itself as data, then inside the static method I cast it to (TestClass *) and run the member methods of the class etc, do the work and when the thread is done I delete the pointer. Something like this:
TestClass * p = new TestClass(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);
What I want to achieve is to make the smart pointer to delete the object automatically when the thread ends because the smart pointer would be out of scope.
When I do it the way I am describing it above the compiler shows this error:
"no suitable conversion function from "std::shared_ptr" to "void *" exists"
shared_ptr
. Oh, let's use this shared pointer. But it's shared and we don't want it to be shared. That's okay, we'll hack around to make it act like it's not shared. But then ... why do it at all? This would make perfect sense if you already had ashared_ptr
or needed one for some reason (maybe the thread needs to extend the object's lifetime). But to create one just to undo its sole purpose ... crazy! – David Schwartz