C++ Ref Count Changes While Destructing Object

丶灬走出姿态 提交于 2019-12-11 05:22:47

问题


I've got a private ref count inside the class SharedObject. SharedObject is a base class for other classes, for example Window. Window is the base class of Editor.

When the ref count reaches 0, because of calling SharedObject::Release(), the SharedObject deletes itself. First we get to the Editor destructor, which shows that the this pointer contains m_refs == 0, but when we get to the Window destructor it is suddenly 1, and when we reach the SharedObject destructor, it is still 1.

I put a breakpoint on the SharedObject::IncRef() method, and it was never called while this happened.

What the?


回答1:


Build with optimizations off, and set a memory breakpoint on your m_refs.




回答2:


Seems like you have memory leak somewhere, maybe even long before this destruction occurs. I use Alleyoop to find leaks. Can help, won't hurt to have that out of the way.

Do you use multiple threads? Maybe it's due to some raw pointer somewhere being grabbed by other thread during destruction.

On a side note, I recommend using boost::intrusive_ptr - very convinient pattern for handling addrefs and releases in shared objects that helps to be consequent with it, but this probably won't solve your problem unless you have a real mess in your code ;)



来源:https://stackoverflow.com/questions/4910129/c-ref-count-changes-while-destructing-object

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