575. the specification of ~shared_ptr is MT-unfriendly, makes implementation assumptions

Section: 23.11.3.2 [util.smartptr.shared.dest], 99 [tr.util.smartptr.shared.dest] Status: CD1 Submitter: Peter Dimov Opened: 2006-04-23 Last modified: 2016-02-10

Priority: Not Prioritized

View all other issues in [util.smartptr.shared.dest].

View all issues with CD1 status.

Discussion:

[tr.util.smartptr.shared.dest] says in its second bullet:

"If *this shares ownership with another shared_ptr instance (use_count() > 1), decrements that instance's use count."

The problem with this formulation is that it presupposes the existence of an "use count" variable that can be decremented and that is part of the state of a shared_ptr instance (because of the "that instance's use count".)

This is contrary to the spirit of the rest of the specification that carefully avoids to require an use count variable. Instead, use_count() is specified to return a value, a number of instances.

In multithreaded code, the usual implicit assumption is that a shared variable should not be accessed by more than one thread without explicit synchronization, and by introducing the concept of an "use count" variable, the current wording implies that two shared_ptr instances that share ownership cannot be destroyed simultaneously.

In addition, if we allow the interpretation that an use count variable is part of shared_ptr's state, this would lead to other undesirable consequences WRT multiple threads. For example,

p1 = p2;

would now visibly modify the state of p2, a "write" operation, requiring a lock.

Proposed resolution:

Change the first two bullets of [lib.util.smartptr.shared.dest]/1 to:

Add the following paragraph after [lib.util.smartptr.shared.dest]/1:

[Note: since the destruction of *this decreases the number of instances in *this's ownership group by one, all shared_ptr instances that share ownership with *this will report an use_count() that is one lower than its previous value after *this is destroyed. --end note]