问题描述
据我了解,在标准 C++ 中,每当您使用 new 运算符时,您还必须在某些时候使用 delete 运算符以防止内存泄漏.这是因为 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.
推荐答案
对它的长答案是,每次调用 new 时,在某个地方,不知何故,delete必须调用,或者其他一些释放函数(取决于内存分配器等)
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.)
但您不必是提供 delete 调用的人:
But you don't need to be the one supplying the delete call:
- 有 C++ 垃圾收集,形式为 Hans-Boehm Garbage Collector.可能还有其他垃圾收集库.
- 您可以使用智能指针,它使用 RAII(如果指针允许共享访问,则使用引用计数)来确定何时删除对象.一个好的智能指针库是 Boost 的 智能指针.在绝大多数情况下,智能指针可以替代原始指针.
- 一些应用程序框架,例如 Qt,构建对象树,这样框架的对象就存在父子关系堆分配的对象.因此,只需在对象上调用
delete,其所有子对象也将自动被deleted.
- There is garbage collection for C++, in the form of the Hans-Boehm Garbage Collector. There is also probably other garbage collection libraries.
- 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.
- 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
deleteto be called on an object, and all its children will automatically bedeleted 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++ 中的垃圾收集是自动的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)