Std :: shared_ptr, weak count more than expected

In one episode (35:00) Series Advanced STL Stephen T. Lavavey showed that _Weaks, the counter value is 0 determines when to remove the structure _Ref_count, equal to the number of living weak_ptr, plus 1, if there is live shared_ptrs. He explained that this was necessary because of thread safety: if it were _Weaksonly equal to the number weak_ptr, then when the latter weak_ptrwould go out of scope, it would also be necessary to check _Usesthe live counter shared_ptrs to check whether it could be deleted _Ref_count. And this is unacceptable due to the lack of atomicity.

Assuming that _Uses= the number of living shared_ptrs, _Weaks= the number of living weak_ptrs, suppose we have the following scenario:

  • ( _Uses= 0, _Weaks= 1 ): the latter weak_ptris beyond the scope, decrement_Weaks

  • ( _Uses= 0, _Weaks= 0 ): if _Usesequal to 0, delete the _Ref_countstructure

What can go wrong in a multi-threaded application, which forces us to use _Weak= implementation number weak_ptr+ (number shared_ptr? 1: 0)?

+4
source share
1 answer

. A shared_ptr, B weak_ptr. _Uses == 1 _Weaks == 1.

, .

1: ,

B weak_ptr . _Weaks. _Uses == 1, _Weaks == 0. B _Uses, ...

.

A shared_ptr . _Uses. _Uses == 0, _Weaks == 0. _Ref_count.

.

B _Uses. 0. _Ref_count.

_Ref_count. .

2: ,

B weak_ptr . _Uses. 1, . B _Weaks, ...

.

A shared_ptr . _Weaks. 1, . _Uses. _Uses == 0, _Weaks == 1. .

.

B _Weaks. _Uses == 0, _Weaks == 0. .

_Ref_count. .

+3

Source: https://habr.com/ru/post/1674377/


All Articles