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:
- 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
delete
to be called on an object, and all its children will automatically be delete
d as well.
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
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…