设计模式可检测内存泄漏以供参考计数的智能指针 [英] Design pattern to detect memory leaks for reference counted smart pointers

查看:85
本文介绍了设计模式可检测内存泄漏以供参考计数的智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有自己的智能指针类,使用基本的AddRef和Release对引用进行计数.

We have our own smart pointers class which is reference counted using basic AddRef and Release.

在调试时,我能够看到许多对象没有正确释放.我可以看到哪些对象没有被释放,但是很难找到从哪里分配它们.

While debugging I am able to see lot of objects not being released properly. I can see which objects not being released but its hard to find out from which place they get allocated.

有没有好的设计模式来解决这个问题?

Is there any good design pattern to address this problem?

我放置了调试语句以及ADDREF和RELEASE,并且在调用release时可以看到引用计数.在某些情况下,其大于1表示未删除指针.

I have put debug statements and ADDREF and RELEASE and I can see reference count when release is called . In some cases its more than 1, that means pointer is not deleted.

如果我开始在shared_ptr const上放置断点,那么它将被调用数百次,并且很难查明内存泄漏.

If I start putting breakpoints on shared_ptr const , then it will called hundred of times and its difficult to pinpoint memory leak.

似乎创建了一些循环引用,这导致了这些泄漏.

It looks like some cyclic references getting created which is causing these leaks.

推荐答案

请勿为此使用设计模式.不要仅仅为了检测泄漏而添加代码膨胀.

Don't use design patterns for this. Don't add code bloat just to detect leaks.

使用存储工具.我想到了Valgrind,还有许多用于Windows的商业版本.

Use a memory tool. Valgrind comes to mind, and a number of commercial ones for Windows.

还...

我可以看到哪些对象没有被释放,但是很难找出从哪里分配了它们.

I can see which objects not being released but its hard to find out from which place they get allocated.

为什么?在对象的构造函数中设置一个断点.或改为使用标准指针(std::shared_ptrstd::unique_ptr).

Why? Set a breakpoint in the constructor of the object. Or use the standard pointers instead (std::shared_ptr, std::unique_ptr).

我放置了调试语句以及ADDREF和RELEASE,并且在调用release时可以看到引用计数.在某些情况下,其大于1表示未删除指针.

I have put debug statements and ADDREF and RELEASE and I can see reference count when release is called . In some cases its more than 1, that means pointer is not deleted.

您是否考虑到复制删节(RVO/NRVO)?这似乎更可能是原因.

Are you taking into account copy elision (RVO/NRVO)? This seems more likely to be the cause.

这篇关于设计模式可检测内存泄漏以供参考计数的智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆