Why use new and delete at all?

后端 未结 8 1964
闹比i
闹比i 2020-12-06 19:25

I\'m new to C++ and I\'m wondering why I should even bother using new and delete? It can cause problems (memory leaks) and I don\'t get why I shouldn\'t just initialize a va

相关标签:
8条回答
  • 2020-12-06 19:51

    Another reason may be if you are explicitly calling an external library or API with a C-style interface. Setting up a callback in such cases often means context data must be supplied and returned in the callback, and such an interface usually provides only a 'simple' void* or int*. Allocating an object or struct with new is appropriate for such actions, (you can delete it later in the callback, should you need to).

    0 讨论(0)
  • 2020-12-06 20:00

    For historical and efficiency reasons, C++ (and C) memory management is explicit and manual.

    Sometimes, you might allocate on the call stack (e.g. by using VLAs or alloca(3)). However, that is not always possible, because

    1. stack size is limited (depending on the platform, to a few kilobytes or a few megabytes).
    2. memory need is not always FIFO or LIFO. It does happen that you need to allocate memory, which would be freed (or becomes useless) much later during execution, in particular because it might be the result of some function (and the caller - or its caller - would release that memory).

    You definitely should read about garbage collection and dynamic memory allocation. In some languages (Java, Ocaml, Haskell, Lisp, ....) or systems, a GC is provided, and is in charge of releasing memory of useless (more precisely unreachable) data. Read also about weak references. Notice that most GCs need to scan the call stack for local pointers.

    Notice that it is possible, but difficult, to have quite efficient garbage collectors (but usually not in C++). For some programs, Ocaml -with a generational copying GC- is faster than the equivalent C++ code -with explicit memory management.

    Managing memory explicitly has the advantage (important in C++) that you don't pay for something you don't need. It has the inconvenience of putting more burden on the programmer.

    In C or C++ you might sometimes consider using the Boehm's conservative garbage collector. With C++ you might sometimes need to use your own allocator, instead of the default std::allocator. Read also about smart pointers, reference counting, std::shared_ptr, std::unique_ptr, std::weak_ptr, and the RAII idiom, and the rule of three (in C++, becoming the rule of 5). The recent wisdom is to avoid explicit new and delete (e.g. by using standard containers and smart pointers).

    Be aware that the most difficult situation in managing memory are arbitrary, perhaps circular, graphs (of reference).

    On Linux and some other systems, valgrind is a useful tool to hunt memory leaks.

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