1

The ccpreference notes for std::shared_ptr<T>::use_count has a note about comparision with 1 that I don't quite understand.

In multithreaded environment, this does not imply that the object is safe to modify because accesses to the managed object by former shared owners may not have completed, and because new shared owners may be introduced concurrently, such as by std::weak_ptr::lock.

I don't understand the implications of accesses to the managed object by former shared owners may not have completed. What does this mean? How can a former shared owner access the underlying object if it doesn't actually hold a shared reference anymore?

Deev
  • 471
  • 2
  • 9
  • 2
    `.use_count()` essentially performs `.load(std::memory_order_relaxed)` on an `std::atomic<...>` (the ref count). Look up `memory_order_relaxed`. I've attempted an explanation here: [What do each memory_order mean?](https://stackoverflow.com/a/70585811/2752075). – HolyBlackCat May 20 '22 at 16:42
  • To add to @HolyBlackCat comment, it's a relaxed load here because even if it was sequential, assuming exclusive ownership when `use_count` is `1` can be unsafe, since there's essentially no locking in place. For example, `weak_ptr` *first* obtains a pointer and *then* increments/decrements the use counter. – rustyx May 20 '22 at 17:12

0 Answers0