0

In the GUI thread I created a std::function object that captures shared_from_this() pointer. After that the std::function object was std::moved several times by another thread (but the object has never been copied). And finally, the std::function object was called by the main thread and destroyed by the main thread.

Is it safe to use std::shared ptr this way?

  • 1
    It can be safe or unsafe depending on how you do it... If you have a race condition on accesses on any object, it's unsafe. – curiousguy Apr 11 '20 at 05:51
  • I use it only to ensure that the pointer(and the object) from shared_ptr will not be destroyed while the background thread do its job. – Mikhail Krasnorutsky Apr 11 '20 at 06:10
  • Purely depends on, how it is used? Why do you need to destroy it? it is smart pointer it will get deleted after reference count will be zero. Ideally, the pointer should be deleted by its owner. – Build Succeeded Apr 11 '20 at 11:05

0 Answers0