[英]DTOR not called when using shared_ptr
I'm running into some really strange behavior.我遇到了一些非常奇怪的行为。 One of my classes (Class
A
) holds a shared_ptr to a class Connector
.我的一个类(
A
类)持有一个 shared_ptr 到一个 class Connector
。 Other classes also hold shared_ptr to that Connector
instance.其他类也将 shared_ptr 保存到该
Connector
实例。 I noticed that the Connector
's destructor doesn't get called after everything goes out of scope.我注意到
Connector
的析构函数在 scope 结束后没有被调用。 However, if I hold the Connector
in class A
as a reference instead of a shared_ptr, the destructor is called and everything works out.但是,如果我将 class
A
中的Connector
作为参考而不是 shared_ptr,则调用析构函数并且一切正常。
Sorry for not sharing any code, but it's part of a big codebase and I'm having trouble extracting smaller, relevant bits.很抱歉没有共享任何代码,但它是大型代码库的一部分,我无法提取较小的相关位。
So my question is: do you have any idea why switching from a shared_ptr to a reference member could influence the behavior in that way?所以我的问题是:你知道为什么从 shared_ptr 切换到引用成员会以这种方式影响行为吗? Maybe it has to do with some cyclic DTOR calls due to the various shared_ptr?
由于各种 shared_ptr,它可能与一些循环 DTOR 调用有关?
I appreciate any hints you might have!我很感激你可能有的任何提示!
PS: All base classes have virtual DTORs. PS:所有基类都有虚拟 DTOR。 That's one of the first things I checked..
这是我检查的第一件事..
This happens when you have a cycle.当你有一个周期时,就会发生这种情况。 That means objects point to each other in a cycle, so the reference count never goes to zero.
这意味着对象在一个循环中相互指向,因此引用计数永远不会变为零。 You have to fix the cycle.
你必须修复循环。 C++ specifically has a
weak_ptr
type to use in such situations, which could be useful in your case as well. C++ 特别具有在这种情况下使用的
weak_ptr
类型,这在您的情况下也可能很有用。
However, if I hold the Connector in class A as a reference instead of a
shared_ptr
, the destructor is called and everything works out.但是,如果我将 class A 中的连接器作为参考而不是
shared_ptr
,则调用析构函数并且一切正常。
This possibly means that the ownership is not well thought through and A
should not be an owner.这可能意味着所有权没有经过深思熟虑,
A
不应该是所有者。 People often default to shared_ptr
because it seems easier to use but, in fact, it complicates the ownership system.人们通常默认使用
shared_ptr
,因为它看起来更容易使用,但实际上它使所有权系统复杂化。 In many cases, you could have a single owner object, holding a unique_ptr
, and everyone else could refer to the object without owning it.在许多情况下,您可能只有一个所有者 object,持有一个
unique_ptr
,其他人可以在不拥有它的情况下引用 object。 This could be done with non-owning raw pointers, etc.这可以通过非拥有的原始指针等来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.