据我了解,在标准 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:
delete
,其所有子对象也将自动被 delete
d.delete
to be called on an object, and all its children will automatically be delete
d 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++ 中的垃圾收集是自动的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!