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
*this
is empty or shares ownership with anothershared_ptr
instance (use_count()
> 1), there are no side effects.- Otherwise, if
*this
owns an objectp
and a deleterd
,d(p)
is called.Otherwise,
*this
owns a pointerp
, and deletep
is called.[Note: Since the destruction of
*this
decreases the number of instances that share ownership with *this by one, after*this
has been destroyed allshared_ptr
instances that shared ownership with*this
will 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