Why use new and delete at all?

后端 未结 8 1965
闹比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:33

    First, if you don't need dynamic allocation, don't use it.

    The most frequent reason for needing dynamic allocation is that the object will have a lifetime which is determined by the program logic rather than lexical scope. The new and delete operators are designed to support explicitly managed lifetimes.

    Another common reason is that the size or structure of the "object" is determined at runtime. For simple cases (arrays, etc.) there are standard classes (std::vector) which will handle this for you, but for more complicated structures (e.g. graphs and trees), you'll have to do this yourself. (The usual technique here is to create a class representing the graph or tree, and have it manage the memory.)

    And there is the case where the object must be polymorphic, and the actual type won't be known until runtime. (There are some tricky ways of handling this without dynamic allocation in the simplest cases, but in general, you'll need dynamic allocation.) In this case, std::unique_ptr might be appropriate to handle the delete, or if the object must be shared, std::shared_ptr (although usually, objects which must be shared fall into the first category, above, and so smart pointers aren't appropriate).

    There are probably other reasons as well, but these are the three that I've encountered the most often.

提交回复
热议问题