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

一笑奈何 提交于 2019-12-07 01:19:36

问题


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();

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/38426719/are-weak-pointers-guaranteed-to-have-expired-by-the-time-the-stdshared-ptr-del

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!