C++ dynamically allocated memory

前端 未结 8 1909
难免孤独
难免孤独 2020-12-10 16:16

I don\'t quite get the point of dynamically allocated memory and I am hoping you guys can make things clearer for me.

First of all, every time we allocate memory we

8条回答
  •  眼角桃花
    2020-12-10 16:51

    In a nutshell, dynamically allocated object's lifetime is controlled by you and not by the language. This allows you to let it live as long as it is required (as opposed to end of the scope), possibly determined by a condition that can only be calculated at run-rime.

    Also, dynamic memory is typically much more "scalable" - i.e. you can allocate more and/or larger objects compared to stack-based allocation.

    The allocation essentially "marks" a piece of memory so no other object can be allocated in the same space. De-allocation "unmarks" that piece of memory so it can be reused for later allocations. If you fail to deallocate memory after it is no longer needed, you get a condition known as "memory leak" - your program is occupying a memory it no longer needs, leading to possible failure to allocate new memory (due to the lack of free memory), and just generally putting an unnecessary strain on the system.

提交回复
热议问题