-1

Assume we have a std::shared_ptr<int> sptr in thread1;

Thread 1 return and trigger destructor of sptr;

By the mean time thread2 called a constructor to copy sptr;

How could std::shared_ptr in multi-thread with a single atomic could guareente that this code would not crush in this race condition?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 1
    Does this answer your question? [std::shared\_ptr thread safety explained](https://stackoverflow.com/questions/9127816/stdshared-ptr-thread-safety-explained) – thedemons Nov 07 '22 at 08:59
  • That's a rather bad example, as one almost *never* need a pointer to a single `int`. – Some programmer dude Nov 07 '22 at 09:00
  • "How could std::shared_ptr in multi-thread with a single atomic" what do you mean with "a single atomic" ? The refcounting is specified to be thread safe, whether there is one atomic or something else is up to the implmentation afaik. There is no race condition – 463035818_is_not_an_ai Nov 07 '22 at 09:02
  • 2
    It is not safe to use the same `shared_ptr` instance in multiple threads. That is not how it is meant to be used. You should use copies of `shared_ptr` in each thread, so that the situation you describe is impossible. Then it is guaranteed that the last `shared_ptr` to be destroyed (and only that) will destroy the managed object. – user17732522 Nov 07 '22 at 09:14

1 Answers1

0

There is a problem with this question.

  • Thread 1 has a std::shared_ptr<int> sptr - ok.
  • Thread 1 returns, sptr goes out of scope - ok.
  • This causes the object held by sptr to be destroyed - ok, but this means that there are no other copies of sptr anywhere, or they would have kept the contained object alive.
  • Thread 2 copies sptr - from where? We just agreed that the last copy of the shared pointer went out of scope, that means that there is nowhere for thread 2 to copy it from.

So there is something wrong with the premise of your question.

You may be tempted to say: "Oh, but I has a pointer to sptr, and thread 2 tried to copy it through that", the answer to that is that you should not have pointers (or references) to shared pointers. The entire point of their existence is that you pass them by value - if you fail to do that, then you violate the contract and they no longer guarantee safety.

Now, it is occasionally the right choice to pass a pointer (most commonly to the contained object) to some function that can't use shared pointers (often old C-style APIs). BUT! Be aware that when you do so, you assume the full responsibility for maintaining the lifetime of the shared pointer and its contained object for as long as that raw pointer is in use.

Frodyne
  • 3,547
  • 6
  • 16