避免内存泄漏 [英] Avoiding memory leaks

查看:102
本文介绍了避免内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用重载运算符来防止C ++中的内存泄漏?

How can we use an overloaded operator to prevent memory leaks in C++?

任何完整的示例.

此致

PKV

推荐答案

如果要避免内存泄漏,请不要使用delete.

If you want to avoid memory leaks, don't use delete.

这似乎是自相矛盾的,但事实是手动内存管理容易出错,最好使用自动(或库)技术.

It may seem paradoxical, but the truth is that manual memory management is error prone, it is best to use automatic (or library) technics.

在C ++中,对于您创建的每个对象,应该有明确的所有权.也就是说,您应该能够确定对象的寿命,可能取决于其他一些寿命.

In C++, for each object that you create, there should be a clear ownership. That is, you should be able to identify the object lifetime, possibly depending on some others.

第一步是避免动态分配内存:如果您不使用new,则没有什么可管理的. .因此,只要可能,使用堆栈.

The first step is to avoid dynamic memory allocation: if you do not use new, you don't have anything to manage -- caveat: some library will hand you memory over and expect you to free it. Therefore, whenever possible, use the stack.

通过使用STL容器(例如std::vector<T>)而不是根据自己的情况避免使用new的情况.

Many use of new can be avoided by using the STL containers (std::vector<T> for example) instead of rolling your own situations.

第二步是谨慎使用new,并且总是在分配内存后立即将其移交给单个所有者.这些所有者包括:

The second step is to use new sparingly, and to always hand over the memory to a single owner immediately after it's been allocated. These owners include:

  • std::unique_ptr (C++0x) or boost::scoped_ptr, in a last resort std::auto_ptr.
  • boost::ptr_vector and the whole collection of Boost.Pointer Container library

单个所有者易于跟踪,并且由于对象的生存期与其所有者相关,因此对象的生存期也易于跟踪.

A single owner is easy to track down, and since the object's lifetime is tied to its owner, therefore the object's lifetime is easy to track down too.

第三步是微妙的一步,即引入共享所有权.它确实使围绕对象生命周期的所有推理复杂化,并引入了引用循环的风险,这实际上意味着内存泄漏.在某些情况下是必需的,但最好避免.

The third step is the delicate one, the introduction of shared ownership. It really complicates all reasoning around the object's lifetime, and introduces the risk of cycles of references, which effectively mean memory leaks. They are required in some situations, but best avoided whenever possible.

  • std::shared_ptr(C ++ 0x)或等效的(std::tr1::shared_ptrboost::shared_ptr)
  • std::weak_ptr(C ++ 0x)或等效版本
  • std::shared_ptr (C++0x) or equivalent (std::tr1::shared_ptr, boost::shared_ptr)
  • std::weak_ptr (C++0x) or equivalent

后者用于中断"循环.但是,即使使用关系图,也很难很快理解在何处引入weak_ptr.

The latter is used to "break" cycles. However it can quickly become difficult to understand where to introduce the weak_ptr, even with a graph of the relationships.

正如Tobias所指出的那样,这个习惯用法被称为资源获取是初始化"(RAII),其名称笨拙.一个新的术语正在出现:范围绑定资源管理(SBRM)来描述它的一个子集->将资源绑定到范围.

As noted by Tobias, this idiom is known as Resources Acquisition Is Initialization (RAII), which is awkwardly named. A newer term is emerging: Scoped Bound Resources Management (SBRM) to describe a subset of it --> binding the resources to a scope.

这篇关于避免内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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