Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are weak pointers guaranteed to have expired by the time the std::shared_ptr deleter runs?

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();
like image 805
jacobsa Avatar asked Jul 17 '16 23:07

jacobsa


2 Answers

The standard guarantees nothing. For shared_ptr's destructor, the spec only says:

  • If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects.
  • Otherwise, if *this owns an object p and a deleter d, d(p) is called.
  • Otherwise, *this owns a pointer p, and delete p 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 all shared_ptr instances that shared ownership with *this will report a use_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.

like image 149
Nicol Bolas Avatar answered Sep 24 '22 03:09

Nicol Bolas


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.

like image 20
jacobsa Avatar answered Sep 20 '22 03:09

jacobsa