Is garbage collection automatic in standard C++?

前端 未结 8 2024
情深已故
情深已故 2020-12-08 23:12

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

相关标签:
8条回答
  • 2020-12-08 23:49

    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. 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.

    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.

    0 讨论(0)
  • 2020-12-08 23:49

    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).

    0 讨论(0)
提交回复
热议问题