-1

I was thinking, if the main thread is deleting a shared_ptr, and cause reference count drop to 0, and in the process of deleting the referenced pointer heap memory, and at the same time, another thread is copying a shared_ptr reference (inside the copy constructor already). What would happen then?

Bryan Fok
  • 2,617
  • 2
  • 24
  • 52
  • hey thanks for the -1 and not leaving any comment – Bryan Fok Apr 02 '18 at 06:16
  • 3
    I didn't downvote the question, but if I had to guess, it was probably done because your question is a single run on sentence which is barely readable and doesn't provide any example of the problem you are trying to solve. – Claies Apr 02 '18 at 06:19
  • 1
    Possible duplicate of - https://stackoverflow.com/questions/9127816/stdshared-ptr-thread-safety-explained ? – badola Apr 02 '18 at 06:26

2 Answers2

0

The situation you describe isn't allowed to happen in standard compliant code. In case it does appear in code, you have undefined behavior.

The std::shared_ptr class isn't thread safe. You aren't allowed to access the same instance from 2 threads without synchronization, as that is a race condition.

So, when the counter is read, if it isn't zero, it is incremented and some pointers are copied over.

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
JVApen
  • 10,085
  • 3
  • 26
  • 56
0

I think this blog did answer my question? I am not sure. So if the shared_ptr is copy to the thread, there are no chance that the problem I mention would happen.

shared_ptr must have at least 2 pointers, so it’s bigger than a raw pointer. It also guarantees thread-safety for all methods as long as each thread has its own copy.

Bryan Fok
  • 2,617
  • 2
  • 24
  • 52
  • I think it is very interesting, and it changed the way I always thought about shared_ptr until I try to implement a simple version of it for fun. I think the blog, and the response from Lothar at the below link did answer this question https://stackoverflow.com/questions/9127816/stdshared-ptr-thread-safety-explained – Bryan Fok Apr 02 '18 at 06:48