是垃圾收集自动在标准C ++? [英] Is garbage collection automatic in standard C++?

查看:152
本文介绍了是垃圾收集自动在标准C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,在每次使用新的运营商标准C ++还必须使用delete运算符在某个时候prevent内存泄漏。这是因为在C ++中没有垃圾收集。在.NET中的垃圾收集是自动的,所以没有必要担心内存管理。我的理解是否正确?谢谢你。

From what I understand, in standard C++ whenever you use the new operator you must also use the delete operator at some point to prevent memory leaks. This is because there is no garbage collection in C++. In .NET garbage collection is automatic so there is no need to worry about memory management. Is my understanding correct? Thanks.

推荐答案

长的答案是,每一次叫,冥冥之中,不知何故,删除必须调用,或其他释放函数(取决于内存分配器等。)

The long answer to it is that for every time new is called, somewhere, somehow, delete must be called, or some other deallocation function (depends on the memory allocator etc.)

但你并不需要成为一个供给删除电话:

But you don't need to be the one supplying the delete call:

  1. 有垃圾收集C ++,在汉斯·伯姆的形式垃圾收集器。也有可能是其他垃圾收集库。
  2. 您可以使用智能指针,它使用RAII(和引用计数,如果指针允许共享访问)来决定何时删除对象。一个良好的智能指针库是Boost的智能指针。在案件的绝大多数智能指针可以代替原始指针。
  3. 在一些应用程序框架,如 Qt的,构建对象树,使得在该框架的一个父子关系堆中分配的对象。其结果是,所有需要的是一个删除被称为一个对象,它的所有的孩子将自动为删除 D为好。
  1. There is garbage collection for C++, in the form of the Hans-Boehm Garbage Collector. There is also probably other garbage collection libraries.
  2. You can use smart pointers, which use RAII (and reference counting if the pointer allows shared access) to determine when to delete the object. A good smart pointer library is Boost's smart pointer. Smart pointers in the vast majority of cases can replace raw pointers.
  3. Some application frameworks, like Qt, build object trees, such that there is a parent child relationship for the framework's heap allocated objects. As a result, all is needed is for a delete to be called on an object, and all its children will automatically be deleted as well.

如果你不想使用这些技术,以防止内存泄漏,您可以尝试使用一个内存检查工具。 Valgrind的是特别好,但它只能在Linux

If you don't want to use any of these techniques, to safeguard against memory leaks, you can try using a memory checking tool. Valgrind is particularly good, although it only works on Linux

对于.NET,是的,分配使用 gcnew 表示该内存是由.NET跟踪,所以没有泄漏。然而其他资源,如文件句柄等不通过GC进行管理的。

As for .NET, yes, allocating using gcnew means that the memory is tracked by .NET, so no leaks. Other resources however, like file handles etc. are not managed by the GC.

这篇关于是垃圾收集自动在标准C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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