c++ - Why use new and delete at all? -
c++ - Why use new and delete at all? -
i'm new c++ , i'm wondering why should bother using new , delete? can cause problems (memory leaks) , don't why shouldn't initialize variable without new operator. can explain me? it's hard google specific question.
for historical , efficiency reasons, c++ (and c) memory management explicit , manual.
sometimes, might allocate on call stack (e.g. using vlas or alloca(3)). however, not possible, because
stack size limited (depending on platform, few kilobytes or few megabytes). memory need not fifo or lifo. happen need allocate memory, freed (or becomes useless) much later during execution, in particular because might result of function (and caller - or caller - release memory).you should read garbage collection , dynamic memory allocation. in languages (java, ocaml, haskell, lisp, ....) or systems, gc provided, , in charge of releasing memory of useless (more exactly unreachable) data. read weak references. notice gcs need scan call stack local pointers.
notice possible, difficult, have quite efficient garbage collectors (but not in c++). some programs, ocaml -with generational copying gc- faster equivalent c++ code -with explicit memory management.
managing memory explicitly has advantage (important in c++) don't pay don't need. has inconvenience of putting more burden on programmer.
in c or c++ might consider using boehm's conservative garbage collector. c++ might sometimes need utilize own allocator, instead of default std::allocator. read smart pointers, reference counting, std::shared_ptr, std::unique_ptr, std::weak_ptr, , raii idiom, , rule of three (in c++, becoming rule of 5). recent wisdom avoid explicit new
, delete
(e.g. using standard containers , smart pointers).
be aware hard situation in managing memory arbitrary, perhaps circular, graphs (of reference).
on linux , other systems, valgrind useful tool hunt memory leaks.
c++ memory-management delete-operator
Comments
Post a Comment