C++销毁对象时引用计数发生变化
我在 SharedObject 类中有一个私有引用计数。 SharedObject 是其他类(例如 Window)的基类。 Window是Editor的基类。
当引用计数达到 0 时,由于调用 SharedObject::Release(),SharedObject 会删除自身。首先我们到达Editor析构函数,它显示this指针包含m_refs == 0,但是当我们到达Window析构函数时它突然变成1,当我们到达SharedObject析构函数时它仍然是1。
我设置了一个断点在 SharedObject::IncRef() 方法上,并且在发生这种情况时从未调用它。
什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关闭优化进行构建,并在 m_refs 上设置内存断点。
Build with optimizations off, and set a memory breakpoint on your m_refs.
似乎你在某个地方发生了内存泄漏,甚至可能早在这种破坏发生之前就发生了。我使用 Alleyoop 来查找泄漏。可以帮忙,解决这个问题也没什么坏处。
你使用多线程吗?也许是因为在销毁过程中某个地方的某些原始指针被其他线程抓住了。
顺便说一句,我建议使用 boost::intrusive_ptr - 非常方便的模式来处理共享对象中的 addrefs 和releases,这有助于随之而来,但这可能不会解决你的问题,除非你的代码真的很混乱;)
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 ;)