环或环中哪个共享指针应该是弱指针

Which shared pointer should be weak pointer in a ring or a cycle

如果我们有一个 Parent class 引用了 Child Class(共享指针)并且 Child Class 也引用了 Parent Class(再次使用共享指针)我们必须将这两个智能指针之一设为弱指针。

但是我们如何决定这两个指针中的哪一个应该是弱指针呢?

还有当一个弱指针指向0时(当shared count为0时),是不是一个对象被删除了,而我们可能还需要访问它的情况?好的,我知道至少我们知道该对象不存在并且我们不应该尝试访问它,但这足够了吗?

想想物体的寿命。

如果 Child 不能比 Parent 长寿,那么 Parent 持有一个指向 Child 的共享指针。

共享指针定义了生命周期层次结构。

If we have a Parent class that has a reference to a Child Class (shared pointer) and the Child Class also has a reference to the Parent Class (again with a shared pointer) we have to make one of these two smart pointers a weak pointer.

不,您不必,如果您认为它适合您的设计,您可以

But how we decide which of these two pointers should be a weak pointer?

不需要其他就可以生存和完成工作的对象应该存储弱指针

Also when a weak pointer points to 0 (when the shared count is 0), is not a situation where an object deleted when we may still need access to it? ok, i get that at least we know that the object is not there and that we should not try to access it, but is this enough?

如果两个对象在它们自己还活着时都需要彼此活着,那么在它们各自中保留一个共享指针。当这些对象完成它们的工作时,您只需重置一个共享指针(通常包含在最顶层 class 中的指针),它将创建一个清理循环,如果它们不正确,您的所有实例都会被正确销毁在别处使用。

P.S:我发现对这种情况非常有用的设计是添加 start/stop 成员函数,尤其是当您使用 enable_shared_from_this 时,它不能在构造函数中被调用,您可以获得有关此设计的更多详细信息from boost asio's author