What are the differences among static, dynamic, and automatic allocation?
问题:
回答1:
There will be language-specific details, but the general idea is:
- Static: allocated at program startup, exists for entire life of program
- Automatic: allocated upon entry into a block, exists for duration of that block
Dynamic allocation requires a bit more explanation: it's allocated when you allocate it (e.g. with something like 'new XXX'). In (most implementations of) C++, it'll exist until you explicitly delete it. With most newer languages (e.g. Java, C#) it'll exist until the garbage collector determines that it's no longer accessible, at which time it'll be destroyed automatically.
Not all languages have all three forms of allocation. In some cases (e.g. Java), even if a form of allocation is supported, there are restrictions such as allowing automatic allocation for built-in types, but requiring dynamic allocation for object types (i.e. instances of classes).
回答2:
Static allocation is memory that has been set aside for an application when it is first loaded. This section of memory is kept to be only used with that application, and is made available again once the program is closed.
Dynamic allocation is memory that is allocated as needed, and deallocated/released when it is no longer needed. Heaps and stacks are examples of areas of memory that can be dynamically allocated.