Stack, Static, and Heap in C++

前端 未结 9 2132
温柔的废话
温柔的废话 2020-11-22 05:17

I\'ve searched, but I\'ve not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what\'s its real advantage? What are the

9条回答
  •  天命终不由人
    2020-11-22 05:41

    What are the problems of static and stack?

    The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.

    The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.

    I could write an entire application without allocate variables in the heap?

    Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).

    What garbage collector does ?

    It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.

    Garbage collectors aren't a usual feature of C++ programming.

    What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?

    Learn the C++ mechanisms for deterministic memory deallocation:

    • 'static': never deallocated
    • 'stack': as soon as the variable "goes out of scope"
    • 'heap': when the pointer is deleted (explicitly deleted by the application, or implicitly deleted within some-or-other subroutine)

提交回复
热议问题