If I have a std::shared_ptr<Foo> with a custom deleter, is it guaranteed that all associated weak pointers are seen as expired by the deleter? (I would appreciate it very much if you could cite relevant sections in the standard.)
In other words is the assertion below guaranteed not to fire?
std::weak_ptr<Foo> weak;
std::shared_ptr<Foo> strong{
new Foo,
[&weak] (Foo* f) {
assert(weak.expired());
delete f;
},
};
weak = strong;
strong.reset();
The standard guarantees nothing. For shared_ptr's destructor, the spec only says:
- If
*thisis empty or shares ownership with anothershared_ptrinstance (use_count()> 1), there are no side effects.- Otherwise, if
*thisowns an objectpand a deleterd,d(p)is called.Otherwise,
*thisowns a pointerp, and deletepis called.[Note: Since the destruction of
*thisdecreases the number of instances that share ownership with *this by one, after*thishas been destroyed allshared_ptrinstances that shared ownership with*thiswill report ause_count()that is one less than its previous value. —end note ]
And reset is defined in terms of swapping a shared_ptr into a temporary, which is then destroyed.
So the spec only guarantees that the state of use_count will be zero after the destructor has finished. Exactly when during that process it is set to 0 is not specified.
There is apparently nothing in the C++14 standard that guarantees this. I've now opened a defect report for the standard covering the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With