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.
相关问题
- Sorting 3 numbers without branching [closed]
- Generic Generics in Managed C++
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
Yes you are right, in standard C++ (In managed C++ or other variants it depends) you must use delete after each new. In C#, Java and other garbage-collected languages, this is not necessary (in fact most of them doesn't have an equivalent to the "delete" operator).
You can use C++ with .NET in two ways: managed or unmanaged. In managed mode, .NET's garbage collection will take care of freeing memory on your behalf; in unmanaged mode, you're close to C++'s normal/standard behavior, so you have to take charge of your memory yourself.
Automatic garbage collection is useful, but you can still get memory leaks, as this question shows:
Memory Leaks in C# WPF
It is decreased in .NET and Java, but that doesn't mean it allows bad coding to be taken care of automatically.
So, in C++ you need to explicitly release what you request, and I think that is sometimes better, as you are aware of what is going on. I wish in .NET and Java that the garbage collector did little in Debug mode, to help ensure people are aware of what they are doing.
Correct you have to worry about garbage collection on C++.
And... there is no need to worry about garbage collection on .NET.
Only if you have such intensive and long scripts that you feel need the optimization do you need to focus on that.
Edit: Both asveikau and Pavel Minaev comments are great, thanks! I overgeneralized to pass the message.
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:delete
to be called on an object, and all its children will automatically bedelete
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."there is no garbage collection in C++."
Correct.