How to avoid null-pointers in multi-threading on the same List?

  c++, multithreading

Say, I have a vector of dynamic object pointers and have different threads working on those objects.

It is possible that while one thread is working on an object, the main thread is deleting it. It does this by setting a flag in the object to mark it for deletion and then starting to free up its memory.

I have thought about taking care of this by checking for the flag before each single access to the object, but theoretically the following could happen (example code for illustration, although I am trying to make it reflect the situation as best as possible there could still be errors in it):

object = copyPointerFromVector(someIndex);

---flag set, object cleaned up by main thread and erased from vector 
  object->getValues(something); //crash with access violation

While it is probably rare this of course is still unacceptable. As someone obviously very very rusty with multi-threading, what is the right way of solving this issue?

Source: Windows Questions C++