160 likes | 333 Views
Static and Dynamic Memory. Static Allocation allocated by the compiler at compile timeonce allocated, does not changeDynamic Allocationallocated by program at run timenew' allocates desired amount from heapamount depends on class/type delete' deallocates an object and returns to storage m
E N D
1. Data Structures w/C++ Dick Steflik
Pointers & Dynamic Arrays
2. Static and Dynamic Memory Static Allocation
allocated by the compiler at compile time
once allocated, does not change
Dynamic Allocation
allocated by program at run time
new allocates desired amount from heap
amount depends on class/type
delete deallocates an object and returns to storage manager for reallocation
3. Where or When Static
data stricture sizes are fixed
little chance for storage needs to grow
prototypes
Dynamic
amount of data changes from run to run
data relationships change frequently
4. Pointers a built-in primitive type; 32 bit
used to hold the storage address of a variable
to define a pointer variable
use the * operator in the definition
5. Pointers (cont.) To assign a value to the pointer variable
use the address operator &
6. Pointers (cont.) Note that F15 has not been assigned a value yet
to do this we must use the dereferencing operator *
7. Pointers (cont.) Which is exactly equivalent to:
8. The Big Deal.... Weve been looking at the trivial case
Pointers to primitives arent very useful
things get more interesting with arrays
we can make :
an array that grows as the application needs more room for data
an array that shrinks as the application needs less room for data
and much better with dynamic objects
9. More Pointers
10. Pointers to arrays The name of an array is a pointer to the 0th element of the array (the beginning of the array)
11. Pointers to arrays Pass by reference - in C++ arrays are always pass by reference (there is no pass by value for an array)
this is a big improvement over C
in C to pass an array to a function it had to be passed by passing a pointer to the beginning of the array then doing pointer arithmetic to manipulate the contentsd of the array
12. new returns the address of a piece of dynamically allocated storage
13. Dynamic Arrays arrays can be allocated at run time
14. Dynamic Arrays You can effectively change the size of an array at run-time if it was originally allocated dynamically.
15. Value semantics The value semantics of a class determine how values are copied from one object to another.
In C++ the value semantics consist of two operations:
the assignment operator
the copy constructor
The copy constructor is a constructor that creates and initializes an object to the value of another (existing) object
the copy constructor has one parameter whose type is the same as the class name
16. Copy Constructor
17. Overloaded assignment operator The overloaded assignment operator must do a deep copy of all of the state variables