0

If one creates a shared pointer to an object using std::make_shared, and use a weak pointer to it as an observer. When the reference count of the shared pointer hits zero, the object is not deallocated because the weak pointer keeps it alive. (If I am not mistaken here.) Suppose that after a call of member function lock() on that weak pointer, and it turns out that it has expired. Now the programmer wants to call reset() to trigger destruction of the object, because the object is quite large.

The question is: is reset an atomic operation? If the answer is NO, my next question is that why the standard doesn't requires it being atomic.

John Z. Li
  • 1,893
  • 2
  • 12
  • 19

2 Answers2

0

The object is only deallocated after each weak_ptr that references the object is reset.

You don't modify single weak_ptr from multiple threads, so reset of a single weak_ptr don't need to be atomic.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • The metadata object is only deallocated when the weak reference count reaches zero, but the managed object is deallocated when the strong reference count reaches zero, regardless of how many weak references exist. – Ben Voigt Feb 24 '19 at 02:02
0

C++20 introduces a helper class std::atomic, that guarantees, quote

The partial template specialization of std::atomic for std::weak_ptr allows users to manipulate weak_ptr objects atomically.

If multiple threads of execution access the same std::weak_ptr object without synchronization and any of those accesses uses a non-const member function of weak_ptr then a data race will occur unless all such access is performed through an instance of std::atomic>.

If one is not using C++20, check this SO answer by Chris Jester-Young for workaround.

John Z. Li
  • 1,893
  • 2
  • 12
  • 19