Stack, Static, and Heap in C++

前端 未结 9 2102
温柔的废话
温柔的废话 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:22

    It's been said elaborately, just as "the short answer":

    • static variable (class)
      lifetime = program runtime (1)
      visibility = determined by access modifiers (private/protected/public)

    • static variable (global scope)
      lifetime = program runtime (1)
      visibility = the compilation unit it is instantiated in (2)

    • heap variable
      lifetime = defined by you (new to delete)
      visibility = defined by you (whatever you assign the pointer to)

    • stack variable
      visibility = from declaration until scope is exited
      lifetime = from declaration until declaring scope is exited


    (1) more exactly: from initialization until deinitialization of the compilation unit (i.e. C / C++ file). Order of initialization of compilation units is not defined by the standard.

    (2) Beware: if you instantiate a static variable in a header, each compilation unit gets its own copy.

提交回复
热议问题