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

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

问题描述

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

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.

我做s。利用DevPartner的内存分析,发现许多领域。 Valgrind的是比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天全站免登陆