From: "Louis Lavery"
From: Peter Dimov
From: "Louis Lavery"
void share(T* rpx, long* rpn) { if (pn != rpn) { // Q: why not px != rpx? A: fails when both ==
0
++*rpn; // done before dispose() in case rpn transitively // dependent on *this (bug reported by Ken Johnson) dispose(); px = rpx; pn = rpn; } } // share
...I curious to know what it means by "fails when both == 0".
It's possible that px == rpx == 0, yet pn != rpn.
Yes, I see that, but I can't see what's wrong with using the test "if ( px != rpx )".
Or, to put it another way, if px == rpx == 0 who cares whether pn equals rpn or not?
Two shared_ptr's are either copies of each other (pn == rpn) or they are not (pn != rpn). It is possible for two shared_ptr's to be both zero, yet to have different counts: shared_ptr<int> a; shared_ptr<int> b; // b.use_count() == 1 b = a; // b.use_count() == 2 It's also possible to have two NULL shared_ptr's that have the same count: shared_ptr<int> a; shared_ptr<int> b(a); // b.use_count() == 2 b = a; // b.use_count() == 2 If you change the test to px != rpx, the first example will leave b with the same count. This is not correct since after the assignment a and b are guaranteed to share the same count (and hence use_count() must be at least 2.) I realize that this is a bit confusing; think about it this way. The test is an "optimization." The results of share() must be the same even without the test. -- Peter Dimov Multi Media Ltd.