Why use new and delete at all?

后端 未结 8 1970
闹比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条回答
  •  Happy的楠姐
    2020-12-06 19:50

    The alternative, allocating on the stack, will cause you trouble as stack sizes are often limited to Mb magnitudes and you'll get lots of value copies. You'll also have problems sharing stack-allocated data between function calls.

    There are alternatives: using std::shared_ptr (C++11 onwards) will do the delete for you once the shared pointer is no longer being used. A technique referred to by the hideous acronym RAII is exploited by the shared pointer implementation. I mention it explicitly since most resource cleanup idioms are RAII-based. You can also make use of the comprehensive data structures available in the C++ Standard Template Library which eliminate the need to get your hands too dirty with explicit memory management.

    But formally, every new must be balanced with a delete. Similarly for new[] and delete[].

提交回复
热议问题