No, this is not the correct approach, because it does not protect the scenario where thread 2 deletes the object before thread 1 calls MyFunction.
You currently have a Dangling Pointer bug in your code.
The correct solution is to modify your code to ensure that deletion of the object happens at a time when no other thread can use it. Common approaches to this include:
- Use events to signal when the threads are done using the object, the thread that does the deletion, will block waiting for everyone to say they are done.
- Use reference counting. Have every thread that uses the object "acquire" and "release" the object. The last one that releases it (e.g. when the ref count reaches 0) then have the object delete itself.