简体   繁体   中英

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!

PS: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM