c++ - 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
. Other classes also hold shared_ptr to that Connector
instance. I noticed that the Connector
's destructor doesn't get called after everything goes out of 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.
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? Maybe it has to do with some cyclic DTOR calls due to the various shared_ptr?
I appreciate any hints you might have!
P.S: All base classes have virtual DTORs. 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.
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.
This possibly means that the ownership is not well thought through and A
should not be an owner. People often default to shared_ptr
because it seems easier to use but, in fact, it complicates the ownership system. 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. This could be done with non-owning raw pointers, etc.
推荐阅读
- kentico - 无法在 UIForm 上仅为一个 Header Action 分配事件
- python - 部分初始化的模块“pandas”没有属性“read_csv”(很可能是由于循环导入)
- deep-learning - 使用更大的批量训练矩阵分解问题时损失更高
- jsp - 我们如何将 JSON 数据从 JSP 传输到 Angular 应用程序?
- postgresql - 控制与 postgres 的 chalice IP 连接
- google-bigquery - 我们如何将文件夹从 Google Storage 加载到 Big Query 中?
- .net-core - 如何在 AWS Cloudwatch 上的 Serilog 的结构化日志输出中显示带有替换参数的日志消息
- r - 在 R 中的直方图上拟合朗道分布
- search - Ansible 查找模块无法打印找到匹配模式的文件
- javascript - 无法使用 Angular2-materialize css 和未捕获的错误:在窗口上找不到 Materialize 对象