使用智能指针替换现有的原始指针 [英] Replacing existing raw pointers with smart pointers

查看:188
本文介绍了使用智能指针替换现有的原始指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这可能听起来很蠢。
我有一个应用程序使用原始指针和应用程序中有大量的内存泄漏。

Note: This may sound dumb. I have an application which uses raw pointers and there are lots of memory leaks in the application.

现在我的问题是,现有的原始指针与智能指针。
只是替换它们有助于减少由不释放动态分配的内存而导致的内存泄漏。

Now my question is how easy would it be to replace the existing raw pointers with the smart pointers. And would just replacing them help is reducing memory leaks caused by not freeing dynamically allocated memory.

为了进一步解释,这个应用程序是一个遗留的应用程序,有非常简单的内存泄漏,其中内存将被分配,并且不会在同一个函数本身释放。

To explain a little further, This application is a legacy one and there are very straightforward memory leaks where memory will be allocated and wont be released in same function itself.

我已经使用DevPartner进行了内存分析,发现了很多区域。

I have done an memory analysis using DevPartner and found many areas. Is Valgrind better than Devpartner.

推荐答案

使用智能指针肯定会是清理你的应用程序的好开始,但他们不是一个治愈。大量的内存泄漏可能只是在一个否则精心设计的程序的粗心,但更有可能你有重大的设计问题,内存泄漏是这种情况的症状。当切换到智能指针时,您仍然需要进行设计选择,例如谁拥有此对象,此对象的所有权在多个客户端之间共享和此对象的预期寿命是多少,以便选择适当的智能指针实现给定的场景。但这将是一个好的开始,因为选择适当的风味的智能指针的过程,为不同的情况将迫使你考虑这些事情,并可能会改善你的设计。

Using smart pointers would certainly be a good start to cleaning up your application, but they're not a cure-all. Lots of memory leaks could just be carelessness in an otherwise well designed program, but more likely you have significant design issues and the memory leaks are a symptom of that. When you switch to smart pointers, you still will need to make design choices like "Who owns this object," "Is ownership of this object shared between multiple clients" and "What is the expected lifetime of this object" in order to choose the proper smart pointer implementation for the given scenario. But this will be a good way to start because the process of choosing the proper flavor of smart pointer for different situations will force you to think about these things and will probably improve your design.

这篇关于使用智能指针替换现有的原始指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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