C++销毁对象时引用计数发生变化

发布于 2024-10-16 07:46:34 字数 322 浏览 7 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青萝楚歌 2024-10-23 07:46:34

关闭优化进行构建,并在 m_refs 上设置内存断点。

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

錯遇了你 2024-10-23 07:46:34

似乎你在某个地方发生了内存泄漏,甚至可能早在这种破坏发生之前就发生了。我使用 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 ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文